Java實現網路爬蟲 案例程式碼3:使用webmagic框架獲取天氣預報

新夢想IT發表於2023-02-08




案例3:獲取天氣預報資訊


需求說明


搭建開發環境,實現從“hao123.com”中獲取當地天氣預報資訊,從控制檯輸出結果




分析


訪問網址:

分析網站URL、檔案內容特徵

獲取網頁內容

拆分出需求內容

控制檯輸出結果



搭建WebMagic開發環境


示例程式碼


import us.codecraft.webmagic.Page;

import us.codecraft.webmagic.Site;

import us.codecraft.webmagic.Spider;

import us.codecraft.webmagic.pipeline.ConsolePipeline;

import us.codecraft.webmagic.processor.PageProcessor;


public class WeatherRepo implements PageProcessor{

    // 部分一:抓取網站的相關配置,包括編碼、抓取間隔、重試次數等

    private Site site = Site.me().setRetryTimes(3).setSleepTime(1000);


    @Override

    // process是定製爬蟲邏輯的核心介面,在這裡編寫抽取邏輯

    public void process(Page page) {

        // 部分二:定義如何抽取頁面資訊,並儲存下來

        page.putField("city", 

            page.getHtml().xpath("//span[@class='weather2-item']/text()").toString());

        

        page.putField("info_today", 

            page.getHtml().xpath("//div[@data-hook='weather']/text()").toString());

        page.putField("temperature_today", 

        page.getHtml().xpath("//div[@data-hook='tempera']/text()").toString());

        

        page.putField("info_tomorrow", 

            page.getHtml().xpath("//div[@data-hook='weather-tomorrow']/text()").toString());

        page.putField("temperature_tomorrow", 

        page.getHtml().xpath("//div[@data-hook='tempera-tomorrow']/text()").toString());

    }


    @Override

    public Site getSite() {

        return site;

    }


    public static void main(String[] args) {


        Spider.create(new WeatherRepo())

                //從""開始抓

                .addUrl("")

                .addPipeline(new ConsolePipeline())   // 控制檯輸出

                .run();

    }

}


————————————————


來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/69940641/viewspace-2934421/,如需轉載,請註明出處,否則將追究法律責任。

相關文章