Java实现简单爬虫爬取天气预报

来源:互联网 发布:有线网络 编辑:程序博客网 时间:2024/05/22 04:35

爬虫爬取网页的主要流程是:

1.向目标网页发起请求;

2.对于获取到的html文件进行解析;

3.对解析后的数据进行存储。


本次主要是爬取全国城市未来7天的天气预报,爬取对象为中国天气网,爬取的数据存入文本中。

对于html文件的解析采用Jsoup结合正则表达式。

地区代码参考:https://wenku.baidu.com/view/49166e7265ce050877321331.html


实现代码:

public class Spiderweather {public static void main(String[] args) {List<String> list = null;BufferedReader bufr = null;BufferedWriter bufw = null;try {bufr = new BufferedReader(new FileReader(new File("D:\\bianma.txt")));list = new ArrayList<String>();String line = "";Pattern p = Pattern.compile("\\d{2,}");while ((line = bufr.readLine()) != null) {Matcher m = p.matcher(line);while (m.find())list.add(m.group());}} catch (Exception e1) {e1.printStackTrace();}Iterator<String> it = list.iterator();File file = new File("D:\\forecast.txt");if (!file.exists())try {file.createNewFile();} catch (IOException e1) {e1.printStackTrace();}try {bufw = new BufferedWriter(new FileWriter(file));} catch (IOException e1) {e1.printStackTrace();}String bm = "";while (it.hasNext()) {bm = it.next();String url = "http://www.weather.com.cn/weather/" + bm + ".shtml";try {Document doc = Jsoup.connect(url).get();Elements content = doc.getElementsByClass("con today clearfix");for (Element e : content) {Document conDoc = Jsoup.parse(e.toString());Elements cru = conDoc.getElementsByClass("crumbs fl");Elements sky = content.select("li[class^=sky skyid lv]");bufw.write(cru.text());// 地点bufw.newLine();for (Element sk : sky) {bufw.write(sk.text());bufw.newLine();}bufw.newLine();}bufw.newLine();bufw.flush();} catch (Exception e) {e.printStackTrace();}}try {System.out.println("天气查询完毕!!");if (bufw != null)bufw.close();if (bufr != null)bufr.close();} catch (IOException e) {e.printStackTrace();}}}


爬取到的结果:

北京 > 城区
7日(今天) 多云转晴 6℃/ -5℃ 3-4级转<3级
8日(明天) 晴间多云转晴 6℃/ -4℃ <3级
9日(后天) 多云 6℃/ -3℃ <3级
10日(周日) 多云 5℃/ -5℃ 3-4级转<3级
11日(周一) 晴 3℃/ -8℃ <3级
12日(周二) 晴 2℃/ -6℃ <3级
13日(周三) 多云 4℃/ -5℃ <3级


北京 > 朝阳
7日(今天) 多云转晴 6℃/ -5℃ 4-5级转<3级
8日(明天) 晴 6℃/ -4℃ <3级
9日(后天) 多云 6℃/ -3℃ <3级
10日(周日) 多云 5℃/ -5℃ 3-4级转<3级
11日(周一) 晴 3℃/ -8℃ <3级
12日(周二) 晴 2℃/ -6℃ <3级
13日(周三) 多云 4℃/ -5℃ <3级


北京 > 顺义
7日(今天) 多云转晴 5℃/ -5℃ 3-4级转<3级
8日(明天) 晴 6℃/ -4℃ <3级
9日(后天) 多云 6℃/ -3℃ <3级
10日(周日) 多云 5℃/ -5℃ 3-4级转<3级
11日(周一) 晴 3℃/ -8℃ <3级
12日(周二) 晴 2℃/ -6℃ <3级
13日(周三) 多云 4℃/ -5℃ <3级


北京 > 怀柔
7日(今天) 多云转晴 5℃/ -7℃ 3-4级转<3级
8日(明天) 晴 6℃/ -6℃ <3级
9日(后天) 多云 6℃/ -5℃ <3级
10日(周日) 多云 5℃/ -7℃ 3-4级转<3级
11日(周一) 晴 3℃/ -10℃ <3级
12日(周二) 晴 2℃/ -8℃ <3级
13日(周三) 多云 4℃/ -7℃ <3级

……


原创粉丝点击