如何使用Html Agility Pack获取img/src或/ hrefs?

iSh*_*how 9 .net html c# html-parsing html-agility-pack

我想使用HTML敏捷包来解析HTML页面中的图像和href链接,但我对XML或XPath不太了解.虽然在许多网站上查找帮助文档,但我无法解决问题.另外,我在VisualStudio 2005中使用C#.我只是不能流利地说英语,所以,我将真诚地感谢能够编写一些有用的代码.

Mar*_*ell 22

主页上的第一个示例非常相似,但请考虑:

 HtmlDocument doc = new HtmlDocument();
 doc.Load("file.htm"); // would need doc.LoadHtml(htmlSource) if it is not a file
 foreach(HtmlNode link in doc.DocumentElement.SelectNodes("//a[@href"])
 {
    string href = link["href"].Value;
    // store href somewhere
 }
Run Code Online (Sandbox Code Playgroud)

所以,你可以想像,对于IMG SRC @,只需更换每一个a具有imghrefsrc.您甚至可以简化为:

 foreach(HtmlNode node in doc.DocumentElement
              .SelectNodes("//a/@href | //img/@src")
 {
    list.Add(node.Value);
 }
Run Code Online (Sandbox Code Playgroud)

对于相对URL处理,请查看Uri该类.

  • 我得到错误:1.4.0.0版本的HtmlAocument对象中没有DocumentElement HtmlAgilitypack foreach(doc.DocumentNode.SelectNodes中的HtmlNode链接("// a [@href]")){HtmlAttribute att = link.Attributes ["href"] ; (3认同)

Sma*_*ess 6

示例和接受的答案是错误的.它不能使用最新版本进行编译.我尝试别的东西:

    private List<string> ParseLinks(string html)
    {
        var doc = new HtmlDocument(); 
        doc.LoadHtml(html);
        var nodes = doc.DocumentNode.SelectNodes("//a[@href]");
        return nodes == null ? new List<string>() : nodes.ToList().ConvertAll(
               r => r.Attributes.ToList().ConvertAll(
               i => i.Value)).SelectMany(j => j).ToList();
    }
Run Code Online (Sandbox Code Playgroud)

这适合我.