25

我刚刚下载了 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));        
    }
4

2 回答 2

45

您可以使用 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

于 2010-01-21T23:56:47.297 回答
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", "") );
       }


    }
于 2010-01-22T00:04:44.547 回答