使用HtmlAgilityPack,验证网页上的元素是否存在

本文关键字:元素 是否 存在 网页 HtmlAgilityPack 验证 使用 | 更新日期: 2023-09-27 18:24:41

假设我在http://google.com,我想验证页面上是否存在id="hplogo"元素(确实存在,它是谷歌标志)。

我想使用HtmlAgilityPack,所以我写了这样的东西:

    HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
    doc.LoadHtml("http://google.com");
    var foo = (from bar in doc.DocumentNode.DescendantNodes()
               where bar.GetAttributeValue("id", null) == "hplogo"
               select bar).FirstOrDefault();
    if (foo == null)
    {
        HasSucceeded = 1;
        MessageBox.Show("not there");
    }
    else
    {
        MessageBox.Show("it's there");
    }
    return HasSucceeded;
}

它应该返回"它在那里"的信息,因为它在那里。但事实并非如此。我做错了什么?

使用HtmlAgilityPack,验证网页上的元素是否存在

方法LoadHtml(html)加载字符串,其中包含用于解析的html内容。这不是要加载的资源的url。所以你正在加载字符串"http://google.com",并试图在其中找到徽标。这当然会给你不存在的结果。

您可以使用WebClient下载资源内容:

WebClient client = new WebClient();
string html = client.DownloadString("http://google.com");
HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(html);