你有一個HTML文檔要從中提取數據,並瞭解這個HTML文檔的結構。css
將HTML解析成一個Document
以後,就能夠使用相似於DOM的方法進行操做。示例代碼:html
@Test public void getData() throws IOException{ 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"); System.out.print(linkHref); String linkText = link.text(); System.out.println(linkText); } }
Elements這個對象提供了一系列相似於DOM的方法來查找元素,抽取並處理其中的數據。具體以下:前端
getElementById(String id)
getElementsByTag(String tag)
getElementsByClass(String className)
getElementsByAttribute(String key)
(and related methods)siblingElements()
, firstElementSibling()
, lastElementSibling()
;nextElementSibling()
, previousElementSibling()
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()
append(String html)
, prepend(String html)
appendText(String text)
, prependText(String text)
appendElement(String tagName)
, prependElement(String tagName)
html(String value)
你想使用相似於CSS或jQuery的語法來查找和操做元素。html5
能夠使用Element.select(String selector)
和 Elements.select(String selector)
方法實現:java
@Test public void getDataSelectorSsyntax() throws IOException{ File input = new File("tmp/input.html"); Document doc = Jsoup.parse(input, "UTF-8", "http://example.com/"); Elements links = doc.select("a[href]");// a with href Elements pngs = doc.select("img[src$=.png]");// img with src ending .png Element masthead = doc.select("div.masthead").first();// div with class=masthead Elements resultLinks = doc.select("h3.r > a"); // direct a after h3 System.out.println("links:"+links); System.out.println("pngs:"+pngs); System.out.println("masthead:"+masthead); System.out.println("resultLinks:"+resultLinks); }
jsoup elements對象支持相似於CSS (或jquery)的選擇器語法,來實現很是強大和靈活的查找功能。.node
這個select
方法在Document
, Element
,或Elements
對象中均可以使用。且是上下文相關的,所以可實現指定元素的過濾,或者鏈式選擇訪問。jquery
Select方法將返回一個Elements
集合,並提供一組方法來抽取和處理結果。css3
tagname
: 經過標籤查找元素,好比:a
ns|tag
: 經過標籤在命名空間查找元素,好比:能夠用 fb|name
語法來查找 <fb:name>
元素#id
: 經過ID查找元素,好比:#logo
.class
: 經過class名稱查找元素,好比:.masthead
[attribute]
: 利用屬性查找元素,好比:[href]
[^attr]
: 利用屬性名前綴來查找元素,好比:能夠用[^data-]
來查找帶有HTML5 Dataset屬性的元素[attr=value]
: 利用屬性值來查找元素,好比:[width=500]
[attr^=value]
, [attr$=value]
, [attr*=value]
: 利用匹配屬性值開頭、結尾或包含屬性值來查找元素,好比:[href*=/path/]
[attr~=regex]
: 利用屬性值匹配正則表達式來查找元素,好比: img[src~=(?i)\.(png|jpe?g)]
*
: 這個符號將匹配全部元素el#id
: 元素+ID,好比: div#logo
el.class
: 元素+class,好比: div.masthead
el[attr]
: 元素+class,好比: a[href]
a[href].highlight
ancestor child
: 查找某個元素下子元素,好比:能夠用.body p
查找在"body"元素下的全部p
元素parent > child
: 查找某個父元素下的直接子元素,好比:能夠用div.content > p
查找 p
元素,也能夠用body > *
查找body標籤下全部直接子元素siblingA + siblingB
: 查找在A元素以前第一個同級元素B,好比:div.head + div
siblingA ~ siblingX
: 查找A元素以前的同級X元素,好比:h1 ~ p
el, el, el
:多個選擇器組合,查找匹配任一選擇器的惟一元素,例如:div.masthead, div.logo
:lt(n)
: 查找哪些元素的同級索引值(它的位置在DOM樹中是相對於它的父節點)小於n,好比:td:lt(3)
表示小於三列的元素:gt(n)
:查找哪些元素的同級索引值大於n
,好比
: div p:gt(2)
表示哪些div中有包含2個以上的p元素:eq(n)
: 查找哪些元素的同級索引值與n
相等,好比:form input:eq(1)
表示包含一個input標籤的Form元素:has(seletor)
: 查找匹配選擇器包含元素的元素,好比:div:has(p)
表示哪些div包含了p元素:not(selector)
: 查找與選擇器不匹配的元素,好比: div:not(.logo)
表示不包含 class="logo" 元素的全部 div 列表:contains(text)
: 查找包含給定文本的元素,搜索不區分大不寫,好比: p:contains(jsoup)
:containsOwn(text)
: 查找直接包含給定文本的元素:matches(regex)
: 查找哪些元素的文本匹配指定的正則表達式,好比:div:matches((?i)login)
:matchesOwn(regex)
: 查找自身包含文本匹配指定正則表達式的元素能夠查看Selector
API參考來了解更詳細的內容nginx
在解析得到一個Document實例對象,並查找到一些元素以後,你但願取得在這些元素中的數據。git
Node.attr(String key)
方法Element.text()
方法Element.html()
, 或 Node.outerHtml()
方法示例:
@Test public void getDataShuX(){ 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元素 System.out.println(link); String text = doc.body().text(); // "An example link"//取得字符串中的文本 System.out.println(text); String linkHref = link.attr("href"); // "http://example.com/"//取得連接地址 System.out.println(linkHref); String linkText = link.text(); // "example""//取得連接地址中的文本 System.out.println(linkText); String linkOuterH = link.outerHtml(); // "<a href="http://example.com"><b>example</b></a>" System.out.println(linkOuterH); String linkInnerH = link.html(); // "<b>example</b>"//取得連接內的html內容 System.out.println(linkInnerH); }
上述方法是元素數據訪問的核心辦法。此外還其它一些方法能夠使用:
這些訪問器方法都有相應的setter方法來更改數據.
你有一個包含相對URLs路徑的HTML文檔,須要將這些相對路徑轉換成絕對路徑的URLs。
base URI
,而後abs:
屬性前綴來取得包含base URI
的絕對路徑。代碼以下: @Test public void getURLs() throws IOException{ Document doc = Jsoup.connect("http://www.open-open.com").get(); Element link = doc.select("a").first(); System.out.println(link); String relHref = link.attr("href"); // == "/" System.out.println(relHref); String absHref = link.attr("abs:href"); // "http://www.open-open.com/" System.out.println(absHref); }
在HTML元素中,URLs常常寫成相對於文檔位置的相對路徑: <a href="/download">...</a>
. 當你使用 Node.attr(String key)
方法來取得a元素的href屬性時,它將直接返回在HTML源碼中指定定的值。
假如你須要取得一個絕對路徑,須要在屬性名前加 abs:
前綴。這樣就能夠返回包含根路徑的URL地址attr("abs:href")
所以,在解析HTML文檔時,定義base URI很是重要。
若是你不想使用abs:
前綴,還有一個方法可以實現一樣的功能 Node.absUrl(String key)
。
這個示例程序將展現如何從一個URL得到一個頁面。而後提取頁面中的全部連接、圖片和其它輔助內容。並檢查URLs和文本信息。
運行下面程序須要指定一個URLs做爲參數
package com.bling.test; import java.io.IOException; import org.jsoup.Jsoup; import org.jsoup.helper.Validate; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; public class ListLinks { public static void main(String[] args) throws IOException { System.out.println(00+"="+args.length); Validate.isTrue(args.length == 1, "usage: supply url to fetch"); String url = args[0]; print("Fetching %s...", url); Document doc = Jsoup.connect(url).get(); Elements links = doc.select("a[href]"); Elements media = doc.select("[src]"); Elements imports = doc.select("link[href]"); print("\nMedia: (%d)", media.size()); for (Element src : media) { if (src.tagName().equals("img")) print(" * %s: <%s> %sx%s (%s)", src.tagName(), src.attr("abs:src"), src.attr("width"), src.attr("height"), trim(src.attr("alt"), 20)); else print(" * %s: <%s>", src.tagName(), src.attr("abs:src")); } print("\nImports: (%d)", imports.size()); for (Element link : imports) { print(" * %s <%s> (%s)", link.tagName(),link.attr("abs:href"), link.attr("rel")); } print("\nLinks: (%d)", links.size()); for (Element link : links) { print(" * a: <%s> (%s)", link.attr("abs:href"), trim(link.text(), 35)); } } private static void print(String msg, Object... args) { System.out.println(String.format(msg, args)); } private static String trim(String s, int width) { if (s.length() > width) return s.substring(0, width-1) + "."; else return s; } }
運行結果:
0=1 Fetching http://news.dbanotes.net/... Media: (36) * script: <http://news.dbanotes.net/jailbreak.js> * img: <http://news.dbanotes.net/logo.png> 32x32 () * img: <http://news.dbanotes.net/s.gif> 10x1 () * img: <http://news.dbanotes.net/grayarrow.png> x () * img: <http://news.dbanotes.net/grayarrow.png> x () * img: <http://news.dbanotes.net/grayarrow.png> x () * img: <http://news.dbanotes.net/grayarrow.png> x () * img: <http://news.dbanotes.net/grayarrow.png> x () * img: <http://news.dbanotes.net/grayarrow.png> x () * img: <http://news.dbanotes.net/grayarrow.png> x () * img: <http://news.dbanotes.net/grayarrow.png> x () * img: <http://news.dbanotes.net/grayarrow.png> x () * img: <http://news.dbanotes.net/grayarrow.png> x () * img: <http://news.dbanotes.net/grayarrow.png> x () * img: <http://news.dbanotes.net/grayarrow.png> x () * img: <http://news.dbanotes.net/grayarrow.png> x () * img: <http://news.dbanotes.net/grayarrow.png> x () * img: <http://news.dbanotes.net/grayarrow.png> x () * img: <http://news.dbanotes.net/grayarrow.png> x () * img: <http://news.dbanotes.net/grayarrow.png> x () * img: <http://news.dbanotes.net/grayarrow.png> x () * img: <http://news.dbanotes.net/grayarrow.png> x () * img: <http://news.dbanotes.net/grayarrow.png> x () * img: <http://news.dbanotes.net/grayarrow.png> x () * img: <http://news.dbanotes.net/grayarrow.png> x () * img: <http://news.dbanotes.net/grayarrow.png> x () * img: <http://news.dbanotes.net/grayarrow.png> x () * img: <http://news.dbanotes.net/grayarrow.png> x () * img: <http://news.dbanotes.net/grayarrow.png> x () * img: <http://news.dbanotes.net/grayarrow.png> x () * img: <http://news.dbanotes.net/grayarrow.png> x () * img: <http://news.dbanotes.net/grayarrow.png> x () * img: <http://news.dbanotes.net/grayarrow.png> x () * img: <http://news.dbanotes.net/grayarrow.png> x () * img: <http://news.dbanotes.net/grayarrow.png> x () * img: <http://news.dbanotes.net/s.gif> 0x10 () Imports: (2) * link <http://news.dbanotes.net/news.css> (stylesheet) * link <http://dbanotes.net/favicon.ico> (shortcut icon) Links: (144) * a: <http://news.dbanotes.net> () * a: <http://news.dbanotes.net/news> (Startup News) * a: <http://news.dbanotes.net/newest> (New) * a: <http://news.dbanotes.net/newcomments> (Comments) * a: <http://news.dbanotes.net/leaders> (Leaders) * a: <http://news.dbanotes.net/submit> (Submit) * a: <http://news.dbanotes.net/x?fnid=1gnh0hqEqi> (Login/Register) * a: <http://news.dbanotes.net/vote?for=17484&dir=up&whence=%6e%65%77%73> () * a: <http://jianshu.io/p/07bc24a09364> (創業這半年) * a: <http://news.dbanotes.net/user?id=laughing> (laughing) * a: <http://news.dbanotes.net/item?id=17484> (discuss) * a: <http://news.dbanotes.net/vote?for=17474&dir=up&whence=%6e%65%77%73> () * a: <http://www.jikexueyuan.com/course/134.html/?hmsr=dbanotes_erweima> (Android二維碼掃描功能實戰開發) * a: <http://news.dbanotes.net/user?id=jikexueyuan> (jikexueyuan) * a: <http://news.dbanotes.net/item?id=17474> (discuss) * a: <http://news.dbanotes.net/vote?for=17480&dir=up&whence=%6e%65%77%73> () * a: <http://blog.segmentfault.com/teambition/1190000000517257> (前端模塊化雜談) * a: <http://news.dbanotes.net/user?id=sf_team> (sf_team) * a: <http://news.dbanotes.net/item?id=17480> (discuss) * a: <http://news.dbanotes.net/vote?for=17464&dir=up&whence=%6e%65%77%73> () * a: <http://jianshu.io/p/8cf2df3fdbf2> (淘寶前端工程師:國內WEB前端開發十日談) * a: <http://news.dbanotes.net/user?id=laughing> (laughing) * a: <http://news.dbanotes.net/item?id=17464> (discuss) * a: <http://news.dbanotes.net/vote?for=17477&dir=up&whence=%6e%65%77%73> () * a: <http://yedingding.com/2014/07/09/deliver-better-product-i.html> (Deliver Better Product (I)) * a: <http://news.dbanotes.net/user?id=yedingding> (yedingding) * a: <http://news.dbanotes.net/item?id=17477> (discuss) * a: <http://news.dbanotes.net/vote?for=17476&dir=up&whence=%6e%65%77%73> () * a: <http://jianshu.io/p/102e2459604e> (UnityTestTool實用解釋) * a: <http://news.dbanotes.net/user?id=laughing> (laughing) * a: <http://news.dbanotes.net/item?id=17476> (discuss) * a: <http://news.dbanotes.net/vote?for=17457&dir=up&whence=%6e%65%77%73> () * a: <http://design.jikexueyuan.com/?hmsr=dbanotes_material> (Android 「Material Design」官方文檔中文版) * a: <http://news.dbanotes.net/user?id=jikexueyuan> (jikexueyuan) * a: <http://news.dbanotes.net/item?id=17457> (1 comment) * a: <http://news.dbanotes.net/vote?for=17468&dir=up&whence=%6e%65%77%73> () * a: <http://shentar.me/dijkstra%E7%AE%97%E6%B3%95%E6%B1%82%E8%A7%A3%E6%9C%80%E7%9F%AD%E8%B7%AF%E5%BE%84%E5%88%86%E6%9E%90/> (Dijkstra算法求解最短路徑分析) * a: <http://news.dbanotes.net/user?id=sandy> (sandy) * a: <http://news.dbanotes.net/item?id=17468> (discuss) * a: <http://news.dbanotes.net/vote?for=17483&dir=up&whence=%6e%65%77%73> () * a: <http://top.jobbole.com/1229/> (SORTING:可視化展現排序算法的原理,支持單步查看) * a: <http://news.dbanotes.net/user?id=vicecity> (vicecity) * a: <http://news.dbanotes.net/item?id=17483> (discuss) * a: <http://news.dbanotes.net/vote?for=17482&dir=up&whence=%6e%65%77%73> () * a: <http://top.jobbole.com/5754/> (若是 Omni 體感遊戲設備能普及的話,是否是能夠幫宅男減肥呢?) * a: <http://news.dbanotes.net/user?id=vicecity> (vicecity) * a: <http://news.dbanotes.net/item?id=17482> (discuss) * a: <http://news.dbanotes.net/vote?for=17462&dir=up&whence=%6e%65%77%73> () * a: <http://www.yyyweb.com/352.html> (15款提升網站可用性和轉化率的工具) * a: <http://news.dbanotes.net/user?id=fineweb> (fineweb) * a: <http://news.dbanotes.net/item?id=17462> (discuss) * a: <http://news.dbanotes.net/vote?for=17478&dir=up&whence=%6e%65%77%73> () * a: <http://segmentfault.com/a/1190000000355928> (PHP 開發者該知道的 5 個 Composer 小技巧) * a: <http://news.dbanotes.net/user?id=sf_team> (sf_team) * a: <http://news.dbanotes.net/item?id=17478> (discuss) * a: <http://news.dbanotes.net/vote?for=17467&dir=up&whence=%6e%65%77%73> () * a: <http://daily.manong.io/2014-07-14> (碼農日報(2014/07/14) - 碼農IO) * a: <http://news.dbanotes.net/user?id=pezy> (pezy) * a: <http://news.dbanotes.net/item?id=17467> (discuss) * a: <http://news.dbanotes.net/vote?for=17475&dir=up&whence=%6e%65%77%73> () * a: <http://www.cnblogs.com/lhb25/p/html5-flah-web-file-uploader.html> (Web Uploader - 功能齊全,完美兼容 IE 的上傳組件) * a: <http://news.dbanotes.net/user?id=wentong> (wentong) * a: <http://news.dbanotes.net/item?id=17475> (discuss) * a: <http://news.dbanotes.net/vote?for=17460&dir=up&whence=%6e%65%77%73> () * a: <http://www.ruanyifeng.com/blog/2014/07/chinese_fonts.html> (中文字體網頁開發指南 - 阮一峯的網絡日誌) * a: <http://news.dbanotes.net/user?id=pezy> (pezy) * a: <http://news.dbanotes.net/item?id=17460> (discuss) * a: <http://news.dbanotes.net/vote?for=17459&dir=up&whence=%6e%65%77%73> () * a: <http://ourjs.com/detail/53c360e2332f1f1808000008> (在nginx中使用lua腳本) * a: <http://news.dbanotes.net/user?id=c52u> (c52u) * a: <http://news.dbanotes.net/item?id=17459> (discuss) * a: <http://news.dbanotes.net/vote?for=17471&dir=up&whence=%6e%65%77%73> () * a: <http://www.yyyweb.com/338.html> (新入行程序員應知的十個祕密) * a: <http://news.dbanotes.net/user?id=fineweb> (fineweb) * a: <http://news.dbanotes.net/item?id=17471> (discuss) * a: <http://news.dbanotes.net/vote?for=17470&dir=up&whence=%6e%65%77%73> () * a: <http://shentar.me/%E4%B8%83%E7%89%9B%E9%95%9C%E5%83%8F%E5%AD%98%E5%82%A8%E8%AF%95%E7%94%A8%E6%89%8B%E8%AE%B0/> (七牛鏡像存儲試用手記) * a: <http://news.dbanotes.net/user?id=sandy> (sandy) * a: <http://news.dbanotes.net/item?id=17470> (discuss) * a: <http://news.dbanotes.net/vote?for=17466&dir=up&whence=%6e%65%77%73> () * a: <http://vdisk.weibo.com/s/aQrMod29ZXpBu> (《破繭成蝶》迷你書) * a: <http://news.dbanotes.net/user?id=websec> (websec) * a: <http://news.dbanotes.net/item?id=17466> (discuss) * a: <http://news.dbanotes.net/vote?for=17465&dir=up&whence=%6e%65%77%73> () * a: <http://blog.jobbole.com/73509/> (Android每週熱點第二十三期) * a: <http://news.dbanotes.net/user?id=vicecity> (vicecity) * a: <http://news.dbanotes.net/item?id=17465> (discuss) * a: <http://news.dbanotes.net/vote?for=17416&dir=up&whence=%6e%65%77%73> () * a: <https://community.emc.com/message/825630#825630> (一站式學習Wireshark(七):Statistics統計工具功能.) * a: <http://news.dbanotes.net/user?id=zoe_magic> (zoe_magic) * a: <http://news.dbanotes.net/item?id=17416> (6 comments) * a: <http://news.dbanotes.net/vote?for=17463&dir=up&whence=%6e%65%77%73> () * a: <http://www.cnblogs.com/lhb25/p/concise-css-framework.html> (Concise - 面向對象的,一致的前端開發框架) * a: <http://news.dbanotes.net/user?id=wentong> (wentong) * a: <http://news.dbanotes.net/item?id=17463> (discuss) * a: <http://news.dbanotes.net/vote?for=17445&dir=up&whence=%6e%65%77%73> () * a: <http://blog.segmentfault.com/alan/1190000000603029> (透支生命三個月) * a: <http://news.dbanotes.net/user?id=sf_team> (sf_team) * a: <http://news.dbanotes.net/item?id=17445> (discuss) * a: <http://news.dbanotes.net/vote?for=17447&dir=up&whence=%6e%65%77%73> () * a: <http://www.javaranger.com/archives/1248> (Maven快速構建springmvc+mybatis項目) * a: <http://news.dbanotes.net/user?id=ppking> (ppking) * a: <http://news.dbanotes.net/item?id=17447> (discuss) * a: <http://news.dbanotes.net/vote?for=17455&dir=up&whence=%6e%65%77%73> () * a: <http://www.geekfan.net/10419/> (將樹莓派打形成音樂播放服務器) * a: <http://news.dbanotes.net/user?id=kkop> (kkop) * a: <http://news.dbanotes.net/item?id=17455> (discuss) * a: <http://news.dbanotes.net/vote?for=17453&dir=up&whence=%6e%65%77%73> () * a: <http://www.importnew.com/12383.html> (Java程序員須知的七個日誌管理工具) * a: <http://news.dbanotes.net/user?id=importnew> (importnew) * a: <http://news.dbanotes.net/item?id=17453> (discuss) * a: <http://news.dbanotes.net/vote?for=17451&dir=up&whence=%6e%65%77%73> () * a: <http://blog.jobbole.com/73134/> (我作自由開發者學到的 4 個教訓) * a: <http://news.dbanotes.net/user?id=vicecity> (vicecity) * a: <http://news.dbanotes.net/item?id=17451> (discuss) * a: <http://news.dbanotes.net/vote?for=17417&dir=up&whence=%6e%65%77%73> () * a: <https://community.emc.com/docs/DOC-36515> (私有云項目實施的四個階段) * a: <http://news.dbanotes.net/user?id=zoe_magic> (zoe_magic) * a: <http://news.dbanotes.net/item?id=17417> (5 comments) * a: <http://news.dbanotes.net/vote?for=17433&dir=up&whence=%6e%65%77%73> () * a: <http://www.yyyweb.com/333.html> (值得一試的8個最佳雲端集成開發環境) * a: <http://news.dbanotes.net/user?id=fineweb> (fineweb) * a: <http://news.dbanotes.net/item?id=17433> (discuss) * a: <http://news.dbanotes.net/vote?for=17428&dir=up&whence=%6e%65%77%73> () * a: <http://segmentfault.com/a/1190000000349384> (30天學習30種新技術系列) * a: <http://news.dbanotes.net/user?id=sf_team> (sf_team) * a: <http://news.dbanotes.net/item?id=17428> (discuss) * a: <http://news.dbanotes.net/vote?for=17410&dir=up&whence=%6e%65%77%73> () * a: <http://lewoer.com/blog/why-move-lewoer-to-usa/> (創業轉型 – 爲何將樂窩轉到美國) * a: <http://news.dbanotes.net/user?id=yang140> (yang140) * a: <http://news.dbanotes.net/item?id=17410> (1 comment) * a: <http://news.dbanotes.net/vote?for=17443&dir=up&whence=%6e%65%77%73> () * a: <http://jianshu.io/p/247fa7f41aef> (技術以外之畫出最合適的趨勢圖) * a: <http://news.dbanotes.net/user?id=laughing> (laughing) * a: <http://news.dbanotes.net/item?id=17443> (discuss) * a: <http://news.dbanotes.net/x?fnid=EuRsZdHc43> (More) * a: <http://dbanotes.net> (DBA Notes) * a: <http://news.dbanotes.net/rss> (RSS) * a: <https://jobsdigg.com/> (Jobs) * a: <http://news.ycombinator.com/> (Hacker News) * a: <https://github.com/nex3/arc/> (GitHub) * a: <http://arclanguage.org/forum> (Arc) * a: <https://itunes.apple.com/us/app/id611072155> (iPhone/iPad) * a: <http://halzhang.github.com/StartupNews/> (Android)