Use the DOM method to traverse a document

Source: Internet
Author: User

You have an HTML document to extract data from and understand the structure of this HTML document. After the method parses HTML into a Document, you can use a method similar to DOM for operations. Sample Code: File input = new File ("/tmp/input.html"); Document doc = Jsoup. parse (input, "UTF-8", "http://example.com/"); Element content = doc. getElementById ("content"); Elements links = content. getElementsByTag ("a"); for (Element link: links) {String linkHref = link. attr ("href"); String linkText = link. text ();} indicates that the Elements object provides a series of DOM-like methods to find Elements, extract and process the data. The details are as follows: getElementById (String id) getElementsByTag (String tag) getElementsByClass (String className) getElementsByAttribute (String key) (and related methods) Element siblings: siblingElements (), firstElementSibling (), lastElementSibling (); nextElementSibling (), previuselementsibling () Graph: parent (), children (), child (int index) Element Data attr (String key) get attributes attr (String key, String value) set attributes () Get all attributes id (), className () and classNames () text () Get text content text (String value) set text content html () to get html (String value) in the element. Set the HTML content in the element outerHtml () to get the html content outside the element data () to get the data content (for example: script and style tags) tag () and tagName () Operations HTML and text append (String html), prepend (String html) appendText (String text), prependText (String text) appendElement (String tagName), prependElement (String tagName) html (String value)

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.