我想使用 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/