使用webmagic搭建一個簡單的爬蟲

來源:互聯網
上載者:User

標籤:chrome   codec   return   包括   方法   processor   .com   位置   int   

剛剛接觸爬蟲,聽說webmagic很不錯,於是就瞭解了一下。

webmagic的是一個無須配置、便於二次開發的爬蟲架構,它提供簡單靈活的API,只需少量代碼即可實現一個爬蟲。

這句話說的真的一點都不假,像我這樣什麼都不懂的人直接下載部署,看了看可以調用的方法,馬上就寫出了第一個爬蟲小程式。

以下是我學習的過程:

首先需要下載jar:http://webmagic.io/download.html

部署好後就建一個class繼承PageProcessor介面,重寫process()方法,即可完成一個爬蟲。

是不是很簡單?

先上代碼,再講解吧。

import us.codecraft.webmagic.Page;import us.codecraft.webmagic.Site;import us.codecraft.webmagic.Spider;import us.codecraft.webmagic.processor.PageProcessor;public class MyProcessor implements PageProcessor {// 抓取網站的相關配置,包括編碼、抓取間隔、重試次數等private Site site = Site.me().setRetryTimes(3).setSleepTime(100);    private static int count =0;@Overridepublic Site getSite() {return site;}@Overridepublic void process(Page page) {        //判斷連結是否符合http://www.cnblogs.com/任意個數字字母-/p/7個數字.html格式if(!page.getUrl().regex("http://www.cnblogs.com/[a-z 0-9 -]+/p/[0-9]{7}.html").match()){//加入滿足條件的連結page.addTargetRequests(page.getHtml().xpath("//*[@id=\"post_list\"]/div/div[@class=‘post_item_body‘]/h3/a/@href").all());}else{                              //擷取頁面需要的內容System.out.println("抓取的內容:"+page.getHtml().xpath("//*[@id=\"Header1_HeaderTitle\"]/text()").get());count ++;}}public static void main(String[] args) {long startTime, endTime;System.out.println("開始爬取...");        startTime = System.currentTimeMillis();Spider.create(new MyProcessor()).addUrl("https://www.cnblogs.com/").thread(5).run();endTime = System.currentTimeMillis();System.out.println("爬取結束,耗時約" + ((endTime - startTime) / 1000) + "秒,抓取了"+count+"條記錄");}}

由於剛開始學,技術有限,所以簡單地爬一下這些文章的作者。

 

 要爬取,首先得知道內容在哪個位置上。在chrome下審查一下元素髮現,文章都在這裡

點進文章後審查元素髮現作者的名字在這裡

知道要爬的內容在哪個位置之後。我們還需要知道怎樣才能拿到這些資料。

這裡說一下webmagic的內容

啟動爬蟲就這句:Spider.create(new MyProcessor()).addUrl("https://www.cnblogs.com/").thread(5).run();//addUrl就是種子url

Page對象就是當前擷取的頁面,

getUrl()可以獲得當前url,

addTargetRequests()就是把連結放入等待爬取

getHtml()獲得頁面的html元素

上面這些很容易就能知道它的意思,不懂得是xpath();

剛開始學,我也不懂,但是chrome懂,所以可以讓它幫我們寫好xpath。

審查元素下,選擇要需要的部分右鍵Copy,選擇Copy XPath,然後在console下粘貼

 

 

關於xpath的教程可以查看https://www.one-tab.com/page/JFPOsHyvQUOQlzZwahc6-Q

關於webmagic的可以查看http://webmagic.io/docs/zh/posts/ch1-overview/

使用webmagic搭建一個簡單的爬蟲

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.