C# 使用HtmlAgilityPack,验证网页上的元素是否存在
假设我处于启用状态,我想验证页面上是否存在一个带有C# 使用HtmlAgilityPack,验证网页上的元素是否存在,c#,html-agility-pack,dom,C#,Html Agility Pack,Dom,假设我处于启用状态,我想验证页面上是否存在一个带有id=“hplogo”的元素(存在的是Google徽标) 我想使用HtmlAgilityPack,所以我写了如下内容: HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument(); doc.LoadHtml("http://google.com"); var foo = (from bar in doc.DocumentNode.Descend
id=“hplogo”
的元素(存在的是Google徽标)
我想使用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;
}
它应该返回“it's there”消息,因为它在那里。但事实并非如此。我做错了什么?方法加载html(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);
对不起,我用VisualStudio编写代码才两个星期,所以我对它的工作原理还很陌生。但我一直在使用它们,我只是不知道如何解释它给我的信息。编辑:好,评论删除经典。