简体   繁体   English

如何使用jsoup访问java中的子元素的属性?

[英]How to access the attribute of a child element in java using jsoup?

Let's assume the HTML file is of the format, 我们假设HTML文件的格式是,

<div>
   <a href"something" title"something"></a>
</div>

I've used jsoup to get all the div tags, I just want to access the child element of div. 我已经使用jsoup来获取所有div标签,我只想访问div的子元素。 I used the .html() method, but it returns a string, and I can't further manipulate it using the methods under Elements. 我使用.html()方法,但它返回一个字符串,我无法使用Elements下的方法进一步操作它。

Since you already have the div's as Elements, use CSS selectors to find the child element, then attr(String) to access the attributes. 由于您已经将div作为元素,因此使用CSS选择器查找子元素,然后使用attr(String)来访问属性。

Elements divs = doc.select("div");
for (Element div : divs)
    String href = div.select("a").first().attr("href");

try this example 试试这个例子

  String html = "<p>An <a href='http://example.com/'><b>example</b></a> link.</p>";
        Document doc = Jsoup.parse(html);
        Element link = doc.select("a").first();

        String text = doc.body().text(); // "An example link"
        String linkHref = link.attr("href"); // "http://example.com/"
        String linkText = link.text(); // "example""

        String linkOuterH = link.outerHtml(); 
            // "<a href="http://example.com"><b>example</b></a>"
        String linkInnerH = link.html(); // "<b>example</b>"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM