如何使用 HtmlAgilityPack 获取子锚点的属性?
How to get attribute of child anchor with HtmlAgilityPack?
我正在学习HtmlAgilitiPack
,我想问你,如何获取值(我想获取这个值):
来自 HTML 页:
<div id="js_citySelectContainer" class="select_container city_select shorten_text replaced">
<span class="dropDownButton ownCity coords">
<a>i want get this value</a>
</span>
</div>
C# 代码:
HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml(html);
Console.writeln(echo i want get this value);
我试过:
doc.DocumentNode.Descendants("span").Where(s => s.GetAttributeValue("class", "") == "dropDownButton ownCity coords").First().InnerText;
但是没有用,你能帮帮我吗?谢谢。
您可以使用 XPATH 语法:
var span = doc.DocumentNode.SelectSingleNode("//span[@class='dropDownButton ownCity coords']");
var anchorText = span.ChildNodes["a"].InnerText;
您也可以使用 LINQ:
var anchorTexts =
from span in doc.DocumentNode.Descendants("span")
where span.GetAttributeValue("class", "") == "dropDownButton ownCity coords"
from anchor in span.Descendants("a")
select anchor.InnerText;
string anchorText = anchorTexts.FirstOrDefault();
我认为您正在尝试获取 span
文本,您需要 a
文本
试试这个
doc.DocumentNode.Descendants("span")
.Where(s => s.GetAttributeValue("class", "") == "dropDownButton ownCity coords")
.First().Descendants("a").First().InnerText;
我正在学习HtmlAgilitiPack
,我想问你,如何获取值(我想获取这个值):
来自 HTML 页:
<div id="js_citySelectContainer" class="select_container city_select shorten_text replaced">
<span class="dropDownButton ownCity coords">
<a>i want get this value</a>
</span>
</div>
C# 代码:
HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml(html);
Console.writeln(echo i want get this value);
我试过:
doc.DocumentNode.Descendants("span").Where(s => s.GetAttributeValue("class", "") == "dropDownButton ownCity coords").First().InnerText;
但是没有用,你能帮帮我吗?谢谢。
您可以使用 XPATH 语法:
var span = doc.DocumentNode.SelectSingleNode("//span[@class='dropDownButton ownCity coords']");
var anchorText = span.ChildNodes["a"].InnerText;
您也可以使用 LINQ:
var anchorTexts =
from span in doc.DocumentNode.Descendants("span")
where span.GetAttributeValue("class", "") == "dropDownButton ownCity coords"
from anchor in span.Descendants("a")
select anchor.InnerText;
string anchorText = anchorTexts.FirstOrDefault();
我认为您正在尝试获取 span
文本,您需要 a
文本
试试这个
doc.DocumentNode.Descendants("span")
.Where(s => s.GetAttributeValue("class", "") == "dropDownButton ownCity coords")
.First().Descendants("a").First().InnerText;