程式扎記: [ Java 代碼範本 ] jsoup - Extract attributes, text, and HTML from elements

標籤

2015年10月25日 星期日

[ Java 代碼範本 ] jsoup - Extract attributes, text, and HTML from elements

Source From Here 
Problem 
After parsing a document, and finding some elements, you'll want to get at the data inside those elements. 

Solution 
* To get the value of an attribute, use the Node.attr(String key) method
* For the text on an element (and its combined children), use Element.text()
* For HTML, use Element.html(), or Node.outerHtml() as appropriate

For example: 
  1. String html = "An example link.
    "
    ;  
  2. Document doc = Jsoup.parse(html);  
  3. Element link = doc.select("a").first();  
  4.   
  5. String text = doc.body().text(); // "An example link"  
  6. String linkHref = link.attr("href"); // "http://example.com/"  
  7. String linkText = link.text(); // "example""  
  8.   
  9. String linkOuterH = link.outerHtml();   
  10.     // "example"  
  11. String linkInnerH = link.html(); // "example"  
Description 
The methods above are the core of the element data access methods. There are additional others: 
* Element.id()
* Element.tagName()
* Element.className() and Element.hasClass(String className)

All of these accessor methods have corresponding setter methods to change the data. 

See also 
* The reference documentation for Element and the collection Elements class 
Working with URLs 
finding elements with the CSS selector syntax

沒有留言:

張貼留言

網誌存檔

關於我自己

我的相片
Where there is a will, there is a way!