【问题标题】:Extract text content of HtmlElement "onclick" attribute with C#用C#提取HtmlElement“onclick”属性的文本内容
【发布时间】:2013-01-30 22:48:07
【问题描述】:

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

【问题讨论】:

  • 这和C#有什么关系
  • 请发布您创建的代码以尝试完成此操作。
  • 添加代码以进一步解释,抱歉。它正在使用网络浏览器控件。
  • 我相信这个问题是因为底层 IE 引擎正在返回一个“脚本对象”并且GetAttributenot 正确返回 DOM 属性(而是它所代表的对象)。虽然完全破解,但很可能可以使用HtmlElement.OuterHtml 将其“作为字符串”提取。我再说一遍:total hack。也可以提取返回的所述“脚本对象”的文本。但第一步是准确确定它是什么类型的对象。
  • 返回 OuterHtml 确实有效,但在我的情况下,这个 div 元素也有子元素,因此它也将这些子元素作为文本返回。

标签: c# html-parsing webbrowser-control


【解决方案1】:

您可以使用 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);
}

【讨论】:

  • 这确实有效。谢谢!我知道 OuterHtml 会返回文本,但没有想到使用索引。
  • @Durn 很高兴为您提供帮助,不要忘记标记您使用的答案。
  • 谢谢!!完美运行!
【解决方案2】:

试试div[j]["onclick"]你用的是什么浏览器?

我已经创建了一个 jsfiddle 试试看它是否适合你

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

【讨论】:

  • 这确实有效,但我使用的是 C# 而不是 javascript。感谢您的意见!
猜你喜欢
  • 2018-04-01
  • 1970-01-01
  • 2014-05-15
  • 2015-09-02
  • 1970-01-01
  • 2018-05-15
  • 2014-03-25
  • 2012-01-23
  • 1970-01-01
相关资源
最近更新 更多