"Jsoup Learning Rites" Extract attributes from elements, text and HTML

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.