Use DOM methods to navigate a document(使用DOM方法来操纵文档)

Problem
You have a HTML document that you want to extract data from(你想从一个html文件中提取数据). You know generally the structure of the HTML document(你知道html的结构).

Solution
Use the DOM-like methods available after parsing HTML into a Document.
(使用类似dom操作的方法来解析html文档)
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();
}

Description
Elements provide a range of DOM-like methods to find elements(提供一系列类似于dom方法来找到元素), and extract and manipulate their data(提取和操纵数据). The DOM getters are contextual(): called on a parent Document they find matching elements under the document; called on a child element they find elements under that child. In this way you can winnow in on the data you want.

Finding elements(查找元素方法)
getElementById(String id)
getElementsByTag(String tag)
getElementsByClass(String className)
getElementsByAttribute(String key) (and related methods)
Element siblings: siblingElements(), firstElementSibling(), lastElementSibling(); nextElementSibling(), previousElementSibling()
Graph: parent(), children(), child(int index)
Element data(元素数据)
attr(String key) to get and attr(String key, String value) to set attributes
attributes() to get all attributes
id(), className() and classNames()
text() to get and text(String value) to set the text content
html() to get and html(String value) to set the inner HTML content
outerHtml() to get the outer HTML value
data() to get data content (e.g. of script and style tags)
tag() and tagName()
Manipulating HTML and text(操作html 和 文本)
append(String html), prepend(String html)
appendText(String text), prependText(String text)
appendElement(String tagName), prependElement(String tagName)
html(String value)

你可能感兴趣的:(document)