如何使用HTML Agility Pack从网站中检索所有图像?

29

我刚刚下载了HTMLAgilityPack,但是文档中没有任何示例。

我正在寻找一种从网站下载所有图片地址的方法,而不是实际的图片文件。

<img src="blabalbalbal.jpeg" />

我需要提取每个img标签的源代码。我只是想了解这个库能提供什么功能。大家都说这是最适合这项工作的最佳工具。
public void GetAllImages()
    {
        WebClient x = new WebClient();
        string source = x.DownloadString(@"http://www.google.com");

        HtmlAgilityPack.HtmlDocument document = new HtmlAgilityPack.HtmlDocument();
        document.Load(source);

                         //I can't use the Descendants method. It doesn't appear.
        var ImageURLS = document.desc
                   .Select(e => e.GetAttributeValue("src", null))
                   .Where(s => !String.IsNullOrEmpty(s));        
    }
2个回答

51

你可以使用 LINQ 来完成,像这样:

var document = new HtmlWeb().Load(url);
var urls = document.DocumentNode.Descendants("img")
                                .Select(e => e.GetAttributeValue("src", null))
                                .Where(s => !String.IsNullOrEmpty(s));

编辑:这段代码现在已经可以工作了;我忘记写了 document.DocumentNode


你的示例中document是什么对象类型?我无法使用.Descendants方法。请检查我的编辑。 - Sergio Tapia
我忘记包含“.DocumentNode”了。 - SLaks
请确保您正在使用最新的测试版,因为LINQ功能是新功能。 - rtpHarry

10

基于他们的一个示例,但使用修改后的XPath:

 HtmlDocument doc = new HtmlDocument();
 List<string> image_links = new List<string>();
 doc.Load("file.htm");
 foreach(HtmlNode link in doc.DocumentElement.SelectNodes("//img"))
 {
    image_links.Add( link.GetAttributeValue("src", "") );
 }

我不了解这个扩展,所以我不确定如何将数组写到其他地方,但这至少可以让您获得数据。 (此外,我肯定没有正确定义数组。抱歉)。

编辑

使用您的示例:

public void GetAllImages()
    {
        WebClient x = new WebClient();
        string source = x.DownloadString(@"http://www.google.com");

        HtmlAgilityPack.HtmlDocument document = new HtmlAgilityPack.HtmlDocument();
        List<string> image_links = new List<string>();
        document.Load(source);

        foreach(HtmlNode link in document.DocumentElement.SelectNodes("//img"))
        {
          image_links.Add( link.GetAttributeValue("src", "") );
       }


    }

1
将其翻译为:List<string> image_links = new List<string>(); foreach (HtmlNode link in doc.DocumentNode.SelectNodes("//img")) { image_links.Add( link.GetAttributeValue("src", "") ); } - TaW

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接