Java实现网络爬虫 案例代码3:使用webmagic框架获取天气预报

案例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元立即加入学习!有需要的朋友戳:


腾讯课堂测试技术学习地址

欢迎转载,但未经作者同意请保留此段声明,并在文章页面明显位置给出原文链接。

发布了9 篇原创文章 · 获赞 1 · 访问量 548

猜你喜欢

转载自blog.csdn.net/sem00000/article/details/105373329
今日推荐