案例3:獲取天氣預報信息
需求說明
搭建開發環境,實現從“hao123.com”中獲取當地天氣預報信息,從控制檯輸出結果
分析
訪問網址:https://www.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())
//從"https://www.hao123.com"開始抓
.addUrl("https://www.hao123.com")
.addPipeline(new ConsolePipeline()) // 控制檯輸出
.run();
}
}
————————————————
超全面的測試IT技術課程,0元立即加入學習!有需要的朋友戳:
騰訊課堂測試技術學習地址
歡迎轉載,但未經作者同意請保留此段聲明,並在文章頁面明顯位置給出原文鏈接。