Java爬虫 获取中国天气网7日天气预报

  • 前言
  • 工具准备
  • 爬取数据
    • 获取日期和星期
    • 获取天气描述
    • 获取温度范围
    • 获取风向及风力
  • 完整代码
  • 引用

前言

项目需要获取7日天气预报,免费好用的接口寻觅不到,搜索一番后发现用简单的爬虫可以实现,在完成python版本后,想着能否用java来实现,一番学习后完成了需求,结果如下

工具准备

在Maven项目中添加相应依赖,这里使用httpclient+jsoup的组合来完成
httpclient用来发送请求,而jsoup用来解析请求结果
两者的详细介绍参考文末引文

<dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpclient</artifactId><version>4.5.13</version>
</dependency>
<dependency><groupId>org.jsoup</groupId><artifactId>jsoup</artifactId><version>1.13.1</version>
</dependency>

爬取数据

首先看到中国天气网的界面如下(随着时间段的不同,界面可能显示不同)
打开控制台看到目标url,url最后的数字标识地区代码,这是我们爬虫的入口,请求头中的User-Agent属性标识自己使用的浏览器。

新建HtmlUtil类用来发送请求,爬取数据需要先从此类获取

package com.ljp.springandpython.utils;import org.apache.http.client.config.RequestConfig;
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.HttpClientBuilder;
import org.apache.http.util.EntityUtils;import java.io.IOException;public class HtmlUtil {public static String getResult(String url) {try (CloseableHttpClient httpClient = HttpClientBuilder.create().build();CloseableHttpResponse response = httpClient.execute(new HttpGetConfig(url))) {String result = EntityUtils.toString(response.getEntity(),"utf-8"); //设置编码,防止乱码return result;} catch (IOException e) {e.printStackTrace();return "";}}
}class HttpGetConfig extends HttpGet {public HttpGetConfig(String url) {super(url);setDefaultConfig();}private void setDefaultConfig() {this.setConfig(RequestConfig.custom().setConnectionRequestTimeout(1000 * 10).setConnectTimeout(1000 * 10).setSocketTimeout(1000 * 10).build());this.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:92.0) Gecko/20100101 Firefox/92.0");}
}

获取日期和星期

在界面中审查元素,找到“4日(今天)”元素,发现为< h1 >标签,另外可以发现在此页面中,h1标签在这里首次出现,那么我们可以获取全部的h1标签,最后只取前7个,提取出日期
jsoup中的select方法可以方便的提取页面中的元素,更多用法参照 jsoup中select的用法

String result=HtmlUtil.getResult("http://www.weather.com.cn/weather/101110200.shtml");
Document document= Jsoup.parse(result);
Elements elements;// 获取日期和星期
elements=document.select("h1");
List<String> dateList=new ArrayList<>();
List<String> dayList=new ArrayList<>();
for (int i = 0; i < 7; i++) {String text=elements.get(i).text();int length=text.length();dateList.add(text.substring(0,length-4));dayList.add(text.substring(length-3,length-1));
}
System.out.println(dateList);
System.out.println(dayList);

获取天气描述

获取天气较为简单,发现天气位于p标签内,class属性为“wea”,接上文代码

// 获取天气
elements=document.select("p[class=wea]");
List<String> weatherList=new ArrayList<>();
for (Element item : elements) {weatherList.add(item.text());
}
System.out.println(weatherList);

获取温度范围

温度范围类似,不再赘述

// 获取温度,最高温和最低温
elements=document.select("p[class=tem]");
int i=0;
List<String> highTempList=new ArrayList<>();
List<String> lowTempList=new ArrayList<>();
for (Element item : elements) {highTempList.add(item.select("span").text()+"℃");lowTempList.add(item.select("i").text());
}
System.out.println(highTempList);
System.out.println(lowTempList);

获取风向及风力

风向和风力有多个子标签嵌套,仔细分析结构

// 获取风向及风力
elements=document.select("p[class=win]");
List<String> windDirectionList1=new ArrayList<>();
List<String> windDirectionList2=new ArrayList<>();
List<String> windSpeedList=new ArrayList<>();
for (Element item : elements) {Element em=item.child(0); //获取em标签,em标签中包含了两个span标签,是需要的风向windDirectionList1.add(em.select("span").get(0).attr("title")); //attr函数用来获取标签内的属性值windDirectionList2.add(em.select("span").get(1).attr("title"));windSpeedList.add(item.select("i").text());
}
System.out.println(windDirectionList1);
System.out.println(windDirectionList2);
System.out.println(windSpeedList);

完整代码

package com.ljp.springandpython.utils;import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;import java.util.*;@SpringBootTest
class HtmlUtilTest {@Testvoid test1(){String result=HtmlUtil.getResult("http://www.weather.com.cn/weather/101110200.shtml");Document document= Jsoup.parse(result);Elements elements;// 获取日期和星期elements=document.select("h1");List<String> dateList=new ArrayList<>();List<String> dayList=new ArrayList<>();for (int i = 0; i < 7; i++) {String text=elements.get(i).text();int length=text.length();dateList.add(text.substring(0,length-4));dayList.add(text.substring(length-3,length-1));}System.out.println(dateList);System.out.println(dayList);// 获取天气elements=document.select("p[class=wea]");List<String> weatherList=new ArrayList<>();for (Element item : elements) {weatherList.add(item.text());}System.out.println(weatherList);// 获取温度,最高温和最低温elements=document.select("p[class=tem]");int i=0;List<String> highTempList=new ArrayList<>();List<String> lowTempList=new ArrayList<>();for (Element item : elements) {highTempList.add(item.select("span").text()+"℃");lowTempList.add(item.select("i").text());}System.out.println(highTempList);System.out.println(lowTempList);// 获取风向及风力elements=document.select("p[class=win]");List<String> windDirectionList1=new ArrayList<>();List<String> windDirectionList2=new ArrayList<>();List<String> windSpeedList=new ArrayList<>();for (Element item : elements) {Element em=item.child(0); //获取em标签,em标签中包含了两个span标签,是需要的风向windDirectionList1.add(em.select("span").get(0).attr("title")); //attr函数用来获取标签内的属性值windDirectionList2.add(em.select("span").get(1).attr("title"));windSpeedList.add(item.select("i").text());}System.out.println(windDirectionList1);System.out.println(windDirectionList2);System.out.println(windSpeedList);// 封装结果,每天一行List<Map<String,String>> list=new ArrayList<>();for (int j = 0; j < 7; j++) {Map<String,String> map=new LinkedHashMap<>();map.put("date",dateList.get(j));map.put("day",dayList.get(j));map.put("weather",weatherList.get(j));map.put("highTemp",highTempList.get(j));map.put("lowTemp",lowTempList.get(j));map.put("windDirection1",windDirectionList1.get(j));map.put("windDirection2",windDirectionList2.get(j));map.put("windSpeed",windSpeedList.get(j));list.add(map);}list.forEach(System.out::println);}}

运行结果:

引用

  • 使用HttpClient和Jsoup实现一个简单爬虫
  • Java爬虫-快速入门 HttpClient+JSoup详解
  • 使用Jsoup的select语法进行元素查找
  • Python爬虫入门实战--------一周天气预报爬取
  • Python爬虫实战(3) | 爬取一周的天气预报信息

Java爬虫 获取中国天气网7日天气预报相关推荐

  1. python爬虫获取中国天气网天气数据 requests BeautifulSoup re

    python获取中国天气网天气数据:http://www.weather.com.cn/textFC/henan.shtml main.py # -*- coding: utf-8 -*- impor ...

  2. php爬虫实时更新天气,Python爬虫获取中国天气网天气预报数据[2018-06-12更新]

    实时天气显示建议用Domoticz内置的DarkSky. 天气预报只能自己获取. 此脚本获取中国天气网七日预报,设备需要自建虚拟硬件,添加虚拟设备,设备类型选择Text文本. 效果: 屏幕快照 201 ...

  3. python 网络爬虫 1.3 获取中国天气网8-15天的天气信息,包含: 日期,天气,温度,风力. 将数据存入文档。

    题目: 获取中国天气网8-15天的天气信息,包含: 日期,天气,温度,风力. 将数据存入文档. 代码: from requests_html import HTMLSessionurl = " ...

  4. html获取中国天气,Json获取中国天气网天气预报的代码

    Json获取中国天气网天气预报的代码 文章作者:网友投稿 发布时间:2010-07-14 14:20:08 来源:网络 获取中国天气网天气的代码 var url=escape(http://m.wea ...

  5. 基于python网络爬虫天气_Python网络爬虫之中国天气网

    大家好,今天我们来讲讲怎么用python对中国天气网进行爬取并且对爬取到的数据进行数据可视化的显示 这就是我们今天要爬取的内容,将中国天气网上的华北.东北等地区七天内的天气数据进行一个爬取,并且对最高 ...

  6. 爬虫实战——中国天气网数据

    这次的爬虫主要目的就是爬取当日中国天气网的即时气候数据.我位于苏州所以爬取的是苏州7月19号的天气. 首先,使用的是beautifulsoup和xpath解析库,因为是纯练习性质,所以分别解析了两趟, ...

  7. java调用天气预报api_java调用中国天气网api获得天气预报信息

    以冰城哈尔滨为例 1.[代码][Java]代码 //通过中国天气api调用 private String getWeatherInfo2(){ StringBuilder info = new Str ...

  8. java获取动态天气api,java调用中国天气网api获得天气预报信息

    //通过中国天气api调用 private String getWeatherInfo2(){ StringBuilder info = new StringBuilder(); try { Defa ...

  9. Java爬取中国天气网实况天气数据

    因实验室需求,需要找一个实况天气API. 百度云.阿里云.腾讯云上边我都去找了,很多平台要么没有,要么要收费(免费的可调用次数太少了).而我在高德开放平台上找到了一个,但是不符合要求,被老师pass掉 ...

最新文章

  1. Vue 2 | Part 4 v-bind绑定元素属性和样式
  2. 刨根问底:C++中宽字符类型(wchar_t)的编码一定是Unicode?长度一定是16位?
  3. php实现复选框删除功能,php怎么实现复选框批量删除
  4. Mavan的配置,以及与IDEA版本不一致,解决办法
  5. 三体云周思进:在红海中寻找蓝海
  6. jQuery 教程02-jQuery 语法
  7. nginx做正向代理http,内网主机yum安装外网资源
  8. Why Ceph and how to use Ceph?
  9. python opencv 找到圆点标定板所有点后通过距离找四个角点
  10. 简单谈一谈git小乌龟操作
  11. c语言标准库详解(五):stdio.h之直接IO/文件定位/错误处理
  12. Dlubal RFEM(有限元分析软件)官方中文版V5.25.01 | 结构设计软件下载 | 有限元分析软件有哪些
  13. Visio Professional 2019 激活方法详解
  14. 迁移学习:他山之石,可以攻玉【VALSE Webinar】Panel实录
  15. word打开老是配置进度_打开word文档显示配置进度怎么办 Word文档提示配置进度解决办法...
  16. 黑马畅购商城---9.Spring Security Oauth2 JWT授权
  17. 经验:常见木马和未授权控制软件的关闭 3
  18. 软考中级软件设计师--下午题
  19. ios 系统状态栏样式修改_iOS_状态栏字体颜色修改(完美解决)
  20. 十年弄潮 ——从《才富》到《中国人力知本》

热门文章

  1. dell precision3551电脑安装win10+ubuntu
  2. Fluent局部坐标系(曲线坐标系)
  3. 2022 学习永远在路上
  4. 数据库建模 — ER建模
  5. Jmeter使用Websocket插件测试SingalR,外加还有阿里云PTS的Jmeter原生测试爬坑日志。
  6. haroopad调整字体大小快捷键
  7. 幽默及顿悟的哲理故事
  8. window10 docker安装nginx报104.18.124.25:443: i/o timeout
  9. canvas实现圆角图片 (处理原图是长方形或正方形)
  10. 推荐几个学习Python的免费网站