jsoup入門

來源:互聯網
上載者:User

標籤:爬取   client   ace   system   多個   標題   outer   gets   xss   

jsoup是一款Java的HTML解析器,主要用來對HTML解析。官網   中文文檔

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

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

 

雖然jsoup也支援從某個地址直接去爬取網頁源碼,但是只支援HTTP,HTTPS協議,支援不夠豐富。

所以,主要還是用來對HTML進行解析。

◆其中,要被解析的HTML可以是一個HTML的字串,可以是一個URL,可以是一個檔案。

org.jsoup.Jsoup把輸入的HTML轉換成一個org.jsoup.nodes.Document對象,然後從Document對象中取出想要的元素。

org.jsoup.nodes.Document繼承了org.jsoup.nodes.Element,Element又繼承了org.jsoup.nodes.Node類。裡面提供了豐富的方法來擷取HTML的元素。

 

◇解析HTML字串

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 doc = Jsoup.connect("http://example.com/").get();String title = doc.title();

其中Jsoup.connect("xxx")方法返回一個org.jsoup.Connection對象。

在Connection對象中,我們可以執行get或者post來執行請求。但是在執行請求之前,

我們可以使用Connection對象來設定一些請求資訊。比如:頭資訊,cookie,請求等待時間,代理等等來類比瀏覽器的行為。

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

 

◇從檔案載入HTML來解析

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

 

◆獲得Document對象後,接下來就是解析Document對象,並從中擷取我們想要的元素了。

Document中提供了豐富的方法來擷取指定元素。

◇使用DOM的方式來取得  

  getElementById(String id):通過id來擷取
  getElementsByTag(String tagName):通過標籤名字來擷取
  getElementsByClass(String className):通過類名來擷取
  getElementsByAttribute(String key):通過屬性名稱字來擷取
  getElementsByAttributeValue(String key, String value):通過指定的屬性名稱字,屬性值來擷取
  getAllElements():擷取所有元素

◇通過類似於css或jQuery的選取器來尋找元素

   使用的是Element類的下記方法:

    public Elements select(String cssQuery)

  通過傳入一個類似於CSS或jQuery的選取器字串,來尋找指定元素。

例子:

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元素

 

選取器的更多文法(可以在org.jsoup.select.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]: 利用屬性值匹配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): 尋找哪些元素的文本匹配指定的Regex,比如:div:matches((?i)login)
  :matchesOwn(regex): 尋找自身包含文本匹配指定Regex的元素
注意  :上述偽選取器索引是從0開始的,也就是說第一個元素索引值為0,第二個元素index為1等

◆通過上面的選取器,我們可以取得一個Elements對象,它繼承了ArrayList對象,裡面放的全是Element對象。

接下來我們要做的就是從Element對象中,取出我們真正需要的內容。

通常有下面幾種方法:

◇Element.text()

  這個方法用來取得一個元素中的文本。

◇Element.html()或Node.outerHtml()

  這個方法用來取得一個元素中的html內容

◇Node.attr(String key)

  獲得一個屬性的值,例如取得超連結<a href="">中href的值

 

 

◆HTML清理

  利用org.jsoup.safety.Cleaner類的clean方法,可以HTML,避免XSS攻擊。

例子:

String unsafe =   "<p><a href=‘http://example.com/‘ onclick=‘stealCookies()‘>Link</a></p>";String safe = Jsoup.clean(unsafe, Whitelist.basic());// now: <p><a href="http://example.com/" rel="nofollow">Link</a></p>

 

◆綜合執行個體:

這個例子將結合HttpClient來爬取頁面的HTML,再利用Jsoup對頁面進行分析,提取極客頭條的內容。

package com.csdn;import java.io.IOException;import org.apache.http.HttpEntity;import org.apache.http.client.ClientProtocolException;import org.apache.http.client.methods.CloseableHttpResponse;import org.apache.http.client.methods.HttpGet;import org.apache.http.impl.client.CloseableHttpClient;import org.apache.http.impl.client.HttpClients;import org.apache.http.util.EntityUtils;import org.jsoup.Jsoup;import org.jsoup.nodes.Document;import org.jsoup.nodes.Element;import org.jsoup.select.Elements;public class HttpClientJsoupTest01 {    //url傳入 "http://www.csdn.net/"     public void get(String url) {                CloseableHttpClient client=HttpClients.createDefault();    //定義一個預設的請求用戶端                HttpGet get=new HttpGet(url);                //定義一個get請求        CloseableHttpResponse response=null;        //定義一個響應                try {            response=client.execute(get);            System.out.println(response.getStatusLine().getStatusCode());//列印響應狀態代碼,200表示成功            HttpEntity entity=response.getEntity();        //擷取響應實體            String html=EntityUtils.toString(entity);    //將實體的內容轉換為字串                        /**             * 接下來就利用jsoup來解析前面取得的html,並擷取csdn首頁的極客頭條欄目下的標題             */            Document document=Jsoup.parse(html);    //利用Jsoup類的靜態方法,將html轉換成一個Document對象            Element element=document.select("div.wrap .left .hot_blog ul").first();    //利用select選取器,取得需要的li元素集合            Elements elements= element.select("a");    //取得a連結的集合                        for (Element element2 : elements) {                System.out.println("標題:"+element2.attr("title")+"        -->>    地址:"+element2.attr("href"));            }                    } catch (ClientProtocolException e) {            // TODO Auto-generated catch block            e.printStackTrace();        } catch (IOException e) {            // TODO Auto-generated catch block            e.printStackTrace();        }finally {            try {                response.close();                client.close();            } catch (IOException e) {                // TODO Auto-generated catch block                e.printStackTrace();            }        }    }}

GitHub下載

 

jsoup入門

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.