C# 我正试图从网站上获取一个图像列表,并将它们保存到硬盘上,但它不起作用
我正在使用HtmlAgilityPack 在此函数中,foreach计数中的imageNodes为0 我不明白为什么列表计数为0 该网站包含许多图片。我想要的是从该站点获取一个图像列表,并在richTextBox1中显示该列表,我还想将该站点的所有图像保存在我的硬盘上 我怎样才能修好它C# 我正试图从网站上获取一个图像列表,并将它们保存到硬盘上,但它不起作用,c#,html-agility-pack,C#,Html Agility Pack,我正在使用HtmlAgilityPack 在此函数中,foreach计数中的imageNodes为0 我不明白为什么列表计数为0 该网站包含许多图片。我想要的是从该站点获取一个图像列表,并在richTextBox1中显示该列表,我还想将该站点的所有图像保存在我的硬盘上 我怎样才能修好它 public void GetAllImages() { // Bing Image Result for Cat, First Page string url = "http://www.bing.
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;
}
}
正如我所看到的,Bing图像的正确分类是sg\t。您可以通过以下Linq查询获得这些HtmlNodes:
List<HtmlNode> imageNodes = doc.DocumentNode.Descendants("img")
.Where(n=> n.Attributes["class"] != null && n.Attributes["class"].Value == "sg_t")
.ToList();
这个列表应该用class='sg\u t'的所有img来填充。快速查看代码中的示例页面/URL会发现,您要查找的图像没有以img\u开头的类类型
<img class="sg_t" src="http://ts2.mm.bing.net/images/thumbnail.aspx?q=4588327016989297&id=db87e23954c9a0360784c0546cd1919c&url=http%3a%2f%2factnowtraining.files.wordpress.com%2f2012%2f02%2fcat.jpg" style="height:133px;top:2px">
我注意到你的代码只针对thumnails。您还需要完整大小的图像URL,它位于每个缩略图周围的锚点中。您需要从a href中提取最终URL,如下所示:
<a href="/images/search?q=cat&view=detail&id=89929E55C0136232A79DF760E3859B9952E22F69&first=0&FORM=IDFRIR" class="sg_tc" h="ID=API.images,18.1"><img class="sg_t" src="http://ts2.mm.bing.net/images/thumbnail.aspx?q=4588327016989297&id=db87e23954c9a0360784c0546cd1919c&url=http%3a%2f%2factnowtraining.files.wordpress.com%2f2012%2f02%2fcat.jpg" style="height:133px;top:2px"></a>
并解码如下所示的位:
url=http%3a%2f%2factnowtraining.files.wordpress.com%2f2012%2f02%2fcat.jpg
解码为:
http://actnowtraining.files.wordpress.com/2012/02/cat.jpg您似乎只选择具有以img开头的class属性的图像-这是否与文档本身相对应?我不清楚为什么除了选择节点的XPATH之外还有一个where node.Name==img,这似乎是多余的。您检查过下载的HTML吗?也许图像是在下载原始HTML后动态加载的,因此您的图像没有图像。