Problem
After parsing a document instance object and finding some elements, you want to get the data in those elements.
Method
- To get the value of a property, you can use the
Node.attr(String key)
method
- For text in an element, you can use the
Element.text()
method
- For HTML content that you want to get in an element or attribute, you can use
Element.html()
, or Node.outerHtml()
method
Example:
String html = "<p>An <a href=‘http://example.com/‘><b>example</b></a> link.</p>";Document doc = Jsoup.parse(html);//解析HTML字符串返回一个Document实现Element link = doc.select("a").first();//查找第一个a元素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>"//取得链接内的html内容
Description
The above approach is the core approach to element data access. In addition, there are other ways to use:
Element.id()
Element.tagName()
Element.className()
andElement.hasClass(String className)
These accessor methods have the appropriate setter method to change the data.
"Jsoup Learning Rites" Extract attributes from elements, text and HTML