【发布时间】:2019-05-17 06:39:17
【问题描述】:
我是 HTML Agility Pack 的新手(以及一般的基于网络的编程)。我正在尝试提取特定的 HTML 行,但我对 HTML Agility Pack 的语法知之甚少,无法理解我写得不正确(并且迷失在他们的文档中)。此处的网址已修改。
string html;
using (WebClient client = new WebClient())
{
html = client.DownloadString("https://google.com/");
}
HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(html);
foreach (HtmlNode img in doc.DocumentNode.SelectNodes("//div[@class='ngg-gallery-thumbnail-box']//div[@class='ngg-gallery-thumbnail']//a"))
{
Debug.Log(img.GetAttributeValue("href", null));
}
return null;
这就是 HTML 的样子
<div id="ngg-image-3" class="ngg-gallery-thumbnail-box" >
<div class="ngg-gallery-thumbnail">
<a href="https://urlhere.png"
// More code here
</a>
</div>
</div>
问题出现在 foreach 行上。我已经尽力在网上匹配示例,但我错过了。 TIA。
【问题讨论】:
-
在调用
img的方法之前,确保它不是null。 -
@SᴇM 你什么意思?我知道问题在于 SelectNodes()。如果我改为编写 SelectNodes("//img") 和 img.GetAttributeValue("src", null)) ,它将打印一堆 URL。但我不想要 HTML 中的所有图像,只想要一个特定的组。
-
Protip:如果不是真的在你的问题中提及
NullReferenceException,请不要提及;我们有太多关于它的不具体问题,你会得到下意识的接近投票。您的问题实际上是关于如何使用 HTML Agility 选择特定节点以及为什么特定的SelectNodes调用没有返回任何节点。 (不,我不知道答案。) -
@JeroenMostert 感谢您的提醒,我继续修改它以希望更清晰。
标签: c# html-agility-pack