使用HtmlElement(Collection)和webbrowser在html中查找特定数据

3 html c# browser

我想找到一个类名为XYZ的div然后在其中我想循环遍历一堆名为ABC的元素.然后抓住里面的链接(一个href)和可能的其他信息.

如何找到XYZ的div webBrowser1.Document.Links和我想要的任何子项?

Sta*_* R. 13

首先你说你想找到一个名为XYZ的div,那你为什么要查看webBrowser1.Documnet.Links?首先找到Div,然后找到其中的链接.

HtmlDocument doc = webBrowser.Document;
HtmlElementCollection col = doc.GetElementsByTagName("div");
foreach (HtmlElement element in col)
{
    string cls = element.GetAttribute("className");
    if (String.IsNullOrEmpty(cls) || !cls.Equals("XYZ"))
        continue;

    HtmlElementCollection childDivs = element.Children.GetElementsByName("ABC");
    foreach (HtmlElement childElement in childDivs)
    {
        //grab links and other stuff same way
    }
}
Run Code Online (Sandbox Code Playgroud)

另请注意使用"className"而不是"class",它将为您提供正确类的名称.仅使用"class"将返回一个空字符串.这在MSDN - SetAttribute中有记录,但在GetAttribute中没有.所以它会引起一些混乱.