[英]How to access the attribute of a child element in java using jsoup?
我們假設HTML文件的格式是,
<div>
<a href"something" title"something"></a>
</div>
我已經使用jsoup來獲取所有div標簽,我只想訪問div的子元素。 我使用.html()
方法,但它返回一個字符串,我無法使用Elements下的方法進一步操作它。
由於您已經將div作為元素,因此使用CSS選擇器查找子元素,然后使用attr(String)來訪問屬性。
Elements divs = doc.select("div");
for (Element div : divs)
String href = div.select("a").first().attr("href");
試試這個例子
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.