HtmlAgilityPack,PCL,没有 XPath:如何通过 class 获取所有元素?
HtmlAgilityPack, PCL, without XPath: How to get all elements by class?
我正在开发的原型需要在网站中提取 deep-nested IFrame。我需要找到所有包含 class 的元素,但是 XPath 在 HtmlAgilityPack 的 PCL 发行版中不可用,所以 this answer does not work. The other approach of using .Descendants() as 建议似乎也不起作用,因为我试过并且Descendants() 似乎没有考虑 children of children,或者如果考虑了,我不知道该怎么做。
site's数据结构是这样的:
html
body
div class mh-container
div class mh-wrapper
div class mh-main
div id main-content
article class post
div class entry-content <- has multiple (2) divs with os_poll
div class os_poll
div class os_widget_container <- TARGET
iframe name os_frame <- need data of the 'src' attribute
我的目标是获取class of os_poll的所有元素,然后访问iframe并获取它们的src数据。由于 XPath 不起作用,而且我不知道如何导航节点以获取 children 的 children(我是 HAP 的新手),我不知道如何处理这个问题。
我找到了一种在 PCL 项目中通过 class 查找元素的方法。但是你将不得不使用 AngleSharp for this, not HtmlAgilityPack, because XPath is not available in PCL。查看 AngleSharp link 了解更多。
Select AngleSharp 中 class 的所有元素:
string html;
using (var client = new HttpClient())
{
string = await client.GetStringAsync("http://your.content.com/some.html");
}
var parser = new HtmlParser();
var doc = parser.Parse(html);
var divs = doc.All.Where(e = > e.LocalName == "div" && e.ClassList.Contains("your-class"));
注意:不要使用我在上面link编辑的网站的数据,因为上面的网站需要JavaScript才能添加os_poll个元素,这样是行不通的.这完全是另一个问题,不在这个问题的范围内。
我正在开发的原型需要在网站中提取 deep-nested IFrame。我需要找到所有包含 class 的元素,但是 XPath 在 HtmlAgilityPack 的 PCL 发行版中不可用,所以 this answer does not work. The other approach of using .Descendants() as
site's数据结构是这样的:
html
body
div class mh-container
div class mh-wrapper
div class mh-main
div id main-content
article class post
div class entry-content <- has multiple (2) divs with os_poll
div class os_poll
div class os_widget_container <- TARGET
iframe name os_frame <- need data of the 'src' attribute
我的目标是获取class of os_poll的所有元素,然后访问iframe并获取它们的src数据。由于 XPath 不起作用,而且我不知道如何导航节点以获取 children 的 children(我是 HAP 的新手),我不知道如何处理这个问题。
我找到了一种在 PCL 项目中通过 class 查找元素的方法。但是你将不得不使用 AngleSharp for this, not HtmlAgilityPack, because XPath is not available in PCL。查看 AngleSharp link 了解更多。
Select AngleSharp 中 class 的所有元素:
string html;
using (var client = new HttpClient())
{
string = await client.GetStringAsync("http://your.content.com/some.html");
}
var parser = new HtmlParser();
var doc = parser.Parse(html);
var divs = doc.All.Where(e = > e.LocalName == "div" && e.ClassList.Contains("your-class"));
注意:不要使用我在上面link编辑的网站的数据,因为上面的网站需要JavaScript才能添加os_poll个元素,这样是行不通的.这完全是另一个问题,不在这个问题的范围内。