我有这个 HTML 代码
<div class="anc-style" onclick="window.open('./view.php?a=foo')"></div>
我想提取“onclick”属性的内容。我试图做类似的事情:
div.GetAttribute("onclick").ToString();
理想情况下会产生字符串
"window.open('./view.php?a=foo')"
但它返回一个 System.__ComObject。
我可以通过将 ("onclick") 更改为 ("class") 来获取类,onclick 是怎么回事?
HtmlElementCollection div = webBrowser1.Document.GetElementsByTagName("div");
for (int j = 0; j < div.Count; j++) {
if (div[j].GetAttribute("class") == "anc-style") {
richTextBox1.AppendText(div[j].GetAttribute("onclick").ToString());
}
}
请您参考如下方法:
您可以使用 htmlDocument 类提取文档标签和提取数据,如下所示。这只是一个例子
string htmlText = "<html><head></head><body><div class=\"anc-style\" onclick=\"window.open('./view.php?a=foo')\"></div></body></html>";
WebBrowser wb = new WebBrowser();
wb.DocumentText = "";
wb.Document.Write(htmlText);
foreach (HtmlElement hElement in wb.Document.GetElementsByTagName("DIV"))
{
//get start and end positions
int iStartPos = hElement.OuterHtml.IndexOf("onclick=\"") + ("onclick=\"").Length;
int iEndPos = hElement.OuterHtml.IndexOf("\">",iStartPos);
//get our substring
String s = hElement.OuterHtml.Substring(iStartPos, iEndPos - iStartPos);
MessageBox.Show(s);
}
