【问题标题】:HtmlAgilityPack, PCL, without XPath: How to get all elements by class?HtmlAgilityPack,PCL,没有 XPath:如何按类获取所有元素?
【发布时间】:2016-10-25 09:40:15
【问题描述】:

我正在处理的原型需要在网站中提取深度嵌套的 IFrame。我需要找到所有包含一个类的元素,但是 XPath 在 HtmlAgilityPack 的 PCL 发行版中不可用,所以this answer 不起作用。使用 .Descendants() 作为this answer 建议的另一种方法似乎也不起作用,因为我尝试过并且 Descendants() 似乎没有考虑孩子的孩子,或者如果确实如此,我不知道怎么做。

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

我的目标是获取所有带有 os_poll 类的元素,然后访问 iframe 并获取它们的 src 数据。由于 XPath 不起作用,而且我不知道如何导航节点以获取子节点(我是 HAP 新手),我不知道如何处理。

【问题讨论】:

    标签: c# xamarin xamarin.forms html-agility-pack


    【解决方案1】:

    我找到了一种在 PCL 项目中按类查找元素的方法。但是您必须为此使用AngleSharp,而不是HtmlAgilityPack,因为XPath is not available in PCL。查看 AngleSharp 链接了解更多信息。

    在 AngleSharp 中按类选择所有元素:

    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"));
    

    注意:不要使用我上面链接的网站的数据,因为上面的网站需要 JavaScript 来添加 os_poll 元素,它不会工作。这完全是另一个问题,超出了这个问题的范围。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多