我正在使用HtmlAgilityPack。我试图从网站获取图像列表,并将它们保存到硬盘,但它不起作用
在这个函数的imageNodes
在foreach计数为0
我不明白为什么这个列表计数为0
该网站包含许多图像。我想要的是从网站上获取图像列表,并在richTextBox1
中显示列表,并且我还希望将网站上的所有图像保存在我的硬盘上。
我该如何解决?
public void GetAllImages()
{
// Bing Image Result for Cat, First Page
string url = "http://www.bing.com/images/search?q=cat&go=&form=QB&qs=n";
// For speed of dev, I use a WebClient
WebClient client = new WebClient();
string html = client.DownloadString(url);
// Load the Html into the agility pack
HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml(html);
// Now, using LINQ to get all Images
List<HtmlNode> imageNodes = null;
imageNodes = (from HtmlNode node in doc.DocumentNode.SelectNodes("//img")
where node.Name == "img"
&& node.Attributes["class"] != null
&& node.Attributes["class"].Value.StartsWith("img_")
select node).ToList();
foreach (HtmlNode node in imageNodes)
{
// Console.WriteLine(node.Attributes["src"].Value);
richTextBox1.Text += node.Attributes["src"].Value + Environment.NewLine;
}
}
你似乎只选择具有以'img_'开头的'class'属性的图像 - 是否与文档本身一致?我不清楚为什么除了用于选择节点的XPATH之外,还有一个'node node.Name ==“img”' - 看起来多余。 – Oded
你检查过下载的HTML吗?下载原始HTML后,图像可能会动态地被下载,所以你的图像没有了。 – JotaBe