我目前尝试使用 HtmlAgilityPack 从 html 页面中提取特定链接。我尝试使用普通的 C# 来强行进入,但事实证明这真的很痛苦。链接都在 <div>
里面全部具有相同类别的标签。这是我所拥有的:
HtmlWeb web = new HtmlWeb();
HtmlDocument html = web.Load(url);
//this should select only the <div> tags with the class acTrigger
foreach (HtmlNode node in html.DocumentNode.SelectNodes("//div[@class='acTrigger']"))
{
//not sure how to dig further in to get the href values from each of the <a> tags
}
网站代码看起来与此类似
<li>
<div class="acTrigger">
<a href="/16014988/d/" onclick="return queueRefinementAnalytics('Category','Battery')">
Battery <em> (1)</em>
</a>
</div>
</li>
<li>
<div class="acTrigger">
<a href="/15568540/d/" onclick="return queueRefinementAnalytics('Category','Brakes')">
Brakes <em> (2)</em>
</a>
</div>
</li>
<li>
<div class="acTrigger">
<a href="/11436914/d/1979-honda-ct90-cables-lines" onclick="return queueRefinementAnalytics('Category','Cables/Lines')">
Cables/Lines <em> (1)</em>
</a>
</div>
</li>
这个页面有很多链接,但是href
我需要包含在那些 <a>
内嵌套在 <div class="acTrigger">
内的标签标签。如果每个 <a>
就很简单了共享独特的类,但不幸的是只有 <div>
标签有类。我需要做的就是捕获其中的每一个 href
并存储它们,以便我以后可以检索它们,转到每个页面,并从每个页面检索更多信息。我只需要朝正确的方向插入即可克服这个困难,然后我也应该能够完成其他页面。我以前没有使用此 HtmlAgilityPack 的经验,并且我发现的所有示例似乎都想从页面中提取所有 URL,而不是特定的 URL。我只需要示例或文档的链接,非常感谢任何帮助。
最佳答案
您应该能够更改您的选择以包含 <a>
标签://div[@class='acTrigger']/a
。这样你的HtmlNode
是你的<a>
标签而不是 div。
要存储链接,您可以使用 GetAttributeValue
.
foreach (HtmlNode node in html.DocumentNode.SelectNodes("//div[@class='acTrigger']/a"))
{
// Get the value of the HREF attribute.
string hrefValue = node.GetAttributeValue( "href", string.Empty );
// Then store hrefValue for later.
}
关于c# - 使用 HtmlAgilityPack C# 检索特定 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42426231/