Jsoup使用DOM方法来遍历一个文档
生活随笔
收集整理的這篇文章主要介紹了
Jsoup使用DOM方法来遍历一个文档
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
要從一個HTML文檔要從中提取數據,并了解這個HTML文檔的結構需要先將HTML解析成一個Document之后,然后使用類似于DOM的方法進行操作。
File input = new File("/file/input.html"); Document doc = Jsoup.parse(input, "UTF-8", "http://baidu.com/");Element content = doc.getElementById("content"); Elements links = content.getElementsByTag("a"); for (Element link : links) {String linkHref = link.attr("href");String linkText = link.text(); }解說
Elements這個對象提供了一系列類似于DOM的方法來查找元素,抽取并處理其中的數據。具體如下:
查找元素
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)元素數據
attr(String key)獲取屬性attr(String key, String value)設置屬性 attributes()獲取所有屬性 id(), className() and classNames() text()獲取文本內容text(String value) 設置文本內容 html()獲取元素內HTMLhtml(String value)設置元素內的HTML內容 outerHtml()獲取元素外HTML內容 data()獲取數據內容(例如:script和style標簽) tag() and tagName()操作HTML和文本
append(String html), prepend(String html) appendText(String text), prependText(String text) appendElement(String tagName), prependElement(String tagName) html(String value)總結
以上是生活随笔為你收集整理的Jsoup使用DOM方法来遍历一个文档的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: MySQL 修改数据
- 下一篇: Java多对多关系示例