【问题标题】:JSOUP - Accessing specific elements within a div classJSOUP - 访问 div 类中的特定元素
【发布时间】:2016-02-24 18:15:09
【问题描述】:

我正在尝试访问 Android 中 HTML 文件中的元素。我已经使用 volley (stringRequest) 检索了文档,现在正在尝试使用 JSOUP 解析文档。

HTML 文档中有一些代码如下:

<div class="theProducts"> 
    <h3>
        <a href="http://www.myproduct.com/myproduct.html" >
            This is the product information I want to access
            <img src="http://prettypictures.myproduct.com/myproduct.jpg" alt=""  />
        </a>
    </h3>
</div>

我可以通过执行以下操作来访问文档中包含的“产品”:

    Document doc = Jsoup.parse(response);

    String title = doc.title();
    Elements productElements = doc.getElementsByClass("theProducts");

    for (Element productElement : productElements) {
        //String name = productElement.attr("name");
        //String content = productElement.attr("content");
    }

所以,我很高兴收到了一系列 productElements。但是,我不确定如何访问我想要的特定元素(即“这是我想要访问的产品”)。我可以看到它嵌套在数组中,但它嵌套得很深。

有没有人可以向我解释要使用的正确语法。我对 DOM 模型不是很熟悉,因此有点困惑。我确实尝试过 doc.getElementsByClass(theProducts.h3) 和 (theProducts#h3) 但这些都不起作用,而是得到了 0 个结果。

我也尝试访问 outerHtml,但这会返回整个 &lt;h3&gt; 部分。

非常感谢任何帮助。

【问题讨论】:

    标签: android html dom jsoup


    【解决方案1】:

    获取所需元素的简单方法是

    Elements els = doc.select("div.theProducts>h3>a");
    for(Element el : els) {
        System.out.println(el.text());
    }
    

    这里的第一行 doc.select("div.theProducts&gt;h3&gt;a") 将给出所有带有类 theProducts 的 div 标签,并且具有 h3 和 child 以及 anchor 作为 h3 元素的孩子。

    编辑::有关选择器标签的更多详细信息

    阅读this link

    【讨论】:

      【解决方案2】:

      再搜索一下,我在这里找到了答案:

      Parse the inner html tags using jSoup

      我现在就去投票!

      在我的问题的上下文中发布答案(在该页面上找到)...

      Elements headlinesCat1 = doc.getElementsByTag("h3");
      for (Element headline : headlinesCat1) {
          Elements importantLinks = headline.getElementsByTag("a");
          for (Element link : importantLinks) {
              String linkHref = link.attr("href");
              String linkText = link.text(); //THIS IS THE TEXT I WANTED...
              System.out.println(linkHref);
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-05-16
        • 2011-08-16
        • 2015-06-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多