1

我有这个 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());   
            }
        }
4

2 回答 2

4

您可以使用 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);
}
于 2013-01-30T23:41:56.637 回答
1

也尝试使用div[j]["onclick"]您使用的浏览器?

我创建了一个可以尝试的 jsfiddle,看看它是否适合你

http://jsfiddle.net/4ZwNs/102/

于 2013-01-30T23:02:49.903 回答