1. 程式人生 > 實用技巧 >JAVA爬蟲使用Css選擇器

JAVA爬蟲使用Css選擇器

Jsoup簡介

jsoup是一款Java的HTML解析器,主要用來對HTML解析。

在爬蟲的時候,當我們用HttpClient之類的框架,獲取到網頁原始碼之後,需要從網頁原始碼中取出我們想要的內容,

就可以使用jsoup這類HTML解析器了。可以非常輕鬆的實現。

    <!-- https://mvnrepository.com/artifact/org.jsoup/jsoup -->
    <dependency>
        <groupId>org.jsoup</groupId>
        <artifactId>jsoup</artifactId>
        <version>1.11.2</version>
    </dependency>

解析Document方式

通過字串解析HTML到Document

String html = "<html><head><title>First parse</title></head>"
  + "<body><p>Parsed HTML into a doc.</p></body></html>";
Document doc = Jsoup.parse(html);

通過URL解析HTML到Document

Document doc = Jsoup.connect("http://example.com")
  .data(
"query", "Java") .userAgent("Mozilla") .cookie("auth", "token") .timeout(3000) .post();

通過檔案解析HTML到Document

File input = new File("/tmp/input.html");
Document doc = Jsoup.parse(input, "UTF-8", "http://example.com/");

資料抽取

使用DOM方法來遍歷一個文件

將HTML解析成一個Document之後,就可以使用類似於DOM的方法進行操作。示例程式碼

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(); }

使用選擇器語法來查詢元素

可以使用Element.select(String selector)Elements.select(String selector)方法實現:

File input = new File("/tmp/input.html");
Document doc = Jsoup.parse(input, "UTF-8", "http://example.com/");
 
Elements links = doc.select("a[href]"); //帶有href屬性的a元素
Elements pngs = doc.select("img[src$=.png]");
  //副檔名為.png的圖片
 
Element masthead = doc.select("div.masthead").first();
  //class等於masthead的div標籤
 
Elements resultLinks = doc.select("h3.r > a"); //在h3元素之後的a元素

說明

jsoup elements物件支援類似於CSS(或jquery)的選擇器語法,來實現非常強大和靈活的查詢功能。.

這個select方法在Document,Element,或Elements物件中都可以使用。且是上下文相關的,因此可實現指定元素的過濾,或者鏈式選擇訪問。

Select方法將返回一個Elements集合,並提供一組方法來抽取和處理結果。

Selector選擇器概述

  • 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)]
  • *: 這個符號將匹配所有元素

Selector選擇器組合使用

  • 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

偽選擇器selectors

  • :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): 查詢自身包含文字匹配指定正則表示式的元素
  • 注意:上述偽選擇器索引是從0開始的,也就是說第一個元素索引值為0,第二個元素index為1等

可以檢視SelectorAPI參考來了解更詳細的內容

從元素抽取屬性,文字和HTML

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內容

處理URLs

你有一個包含相對URLs路徑的HTML文件,需要將這些相對路徑轉換成絕對路徑的URLs。

Document doc = Jsoup.connect("http://www.open-open.com").get();
 
Element link = doc.select("a").first();
String relHref = link.attr("href"); // == "/"
String absHref = link.attr("abs:href"); // "http://www.open-open.com/"