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

新手上路,请多包涵

我想使用HTML agility pack来解析HTML页面中的图片和href链接,但我对XML或XPath了解不多。虽然在许多网站上查找帮助文档,但我无法解决问题。此外,我在 VisualStudio 2005 中使用 C#。而且我不会说流利的英语,所以,我将真诚地感谢能够编写一些有用代码的人。

原文由 iShow 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.6k
2 个回答

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

  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
 }

So you can imagine that for img@src, just replace each a with img , and href with src .您甚至可以简化为:

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

对于相对 url 处理,请查看 Uri 类。

原文由 Marc Gravell 发布,翻译遵循 CC BY-SA 2.5 许可协议

该示例和接受的答案是错误的。它不编译最新版本。我尝试别的东西:

     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();
    }

这对我有用。

原文由 SmallChess 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题