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

标签 c# .net html html-parsing html-agility-pack

我想使用 HTML 敏捷包来解析来自 HTML 页面的图像和 href 链接,但我对 XML 或 XPath 了解不多。尽管在许多网站上查找帮助文档,我还是可以'解决不了问题。另外,我在 VisualStudio 2005 中使用 C#,而且我不会说流利的英语,所以,我将真诚地感谢能编写一些有用代码的人。

最佳答案

first example在主页上做了非常相似的事情,但请考虑:

 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
 }

所以你可以想象对于img@src,只需将每个a替换为img,将href替换为src。 您甚至可以简化为:

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

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

关于c# - 如何使用 Html Agility Pack 获取 img/src 或 a/hrefs?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4835868/

相关文章:

c# - ContextMenuStrip 未正确调整大小

c# - OpenXML 自定义列宽不起作用

c# - 如何在托管 Windows 服务中托管 WCF 服务?

.net - 处理 Owin/Katana 和 Autofac 中的 DI 错误

c# - 如何动态地将图像添加到 DataGridView(每行的特定列)

javascript - 数字的正则表达式仅在 1-24 之间并且还允许小数

c# - 在 KeyValuePair 上的 ItemTemplate 中绑定(bind)不起作用

c# - 将 System.Diagnostics.ProcessStartInfo StandardOutput 读取为字节而不是字符

php - 检查php中两个文本框的值是否相同

javascript - 从不同组件切换事件/非事件类 Angular