使用Jsoup、多线程去国家统计局官网获取全国省市县三级json数据:

package com.imant.crawler.controller;import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.imant.crawler.vo.AreaVo;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.*;/*** 用于去www.stats.gov.cn爬取省市县的数据*/
public class AreaCrawler {private static Gson gson = new GsonBuilder().create();private static String URL_PREFIX = "http://www.stats.gov.cn/tjsj/tjbz/tjyqhdmhcxhfdm/2017/";private static int count = 0;private static final ThreadFactory namedThreadFactory = new ThreadFactoryBuilder().setNameFormat("areaCrawler-pool-%d").build();//创建线程池private static final ExecutorService pool     = new ThreadPoolExecutor(5, 200, 0L,TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(16), namedThreadFactory,new ThreadPoolExecutor.AbortPolicy());private static List<AreaVo> areaVoList = new ArrayList<>();public Document getDocument(String url) throws IOException {try{Connection conn = Jsoup.connect(url).timeout(5000);conn.header("Accept", "*/*");conn.header("Accept-Encoding", "gzip, deflate, br");conn.header("Accept-Language", "zh-CN,zh;q=0.9");conn.header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36");Connection.Response response = null;do {response = conn.execute();if(count > 0){Document doc = Jsoup.connect(url).data("query", "Java").userAgent("Mozilla").cookie("auth", "token").timeout(3000).post();return doc;}}while(response.statusCode() != 200);return  conn.get();}catch (IOException e){throw e;}}public static void main(String[] args) throws InterruptedException, ExecutionException {AreaCrawler t = new AreaCrawler();Document doc = null;do {try{doc = t.getDocument("http://www.stats.gov.cn/tjsj/tjbz/tjyqhdmhcxhfdm/2017/index.html");count = 0;}catch (Exception e){count++;}}while(doc == null);//获取所有的省List<Future>  futureList = new ArrayList<>();Elements provinceElements = doc.select("table.provincetable tbody tr.provincetr td");for(Element element : provinceElements){if (StringUtils.isNotBlank(element.text())) {AreaVo areaVo = new AreaVo();areaVo.setName(element.text());String cityUrl = URL_PREFIX + element.select("td a").get(0).attr("href");String code = element.select("td a").get(0).attr("href").substring(0, 2) + "0000";areaVo.setCode(code);Future future = pool.submit(new CityThread(cityUrl, areaVo));futureList.add(future);}}/*** 等待所有的子线程执行完毕*/for(Future future : futureList){future.get();}//关闭线程池pool.shutdownNow();Collections.sort(areaVoList, Comparator.comparing(AreaVo::getCode));System.out.println(gson.toJson(areaVoList));}private static class CityThread implements Runnable{String url;AreaVo areaVo;public CityThread(String url, AreaVo areaVo){this.url = url;this.areaVo = areaVo;}@Overridepublic void run() {AreaCrawler t = new AreaCrawler();Document cityDocument = null;do{try {cityDocument = t.getDocument(url);count = 0;}catch (Exception e){//e.printStackTrace();count++;}}while(cityDocument == null);Elements cityElements = cityDocument.select("table.citytable tbody tr.citytr");List<AreaVo> cityList = new ArrayList<>();for(Element cityElement :cityElements){AreaVo cityVo = new AreaVo();String cityCode = cityElement.select("td").get(0).text().substring(0,6);String cityName = cityElement.select("td").get(1).text();cityVo.setCode(cityCode);cityVo.setName(cityName);if(cityElement.select("td a").size() > 0){String countyUrl = URL_PREFIX + cityElement.select("td a").get(0).attr("href");Document countyDocument = null;do{try{countyDocument = t.getDocument(countyUrl);count = 0;}catch (Exception e){//e.printStackTrace();count++;}}while(countyDocument == null);Elements countyElements = countyDocument.select("table tbody tr.countytr");List<AreaVo> countyList = new ArrayList<>();for(Element countyElement : countyElements){AreaVo countyVo = new AreaVo();String countyCode = countyElement.select("td").get(0).text().substring(0,6);String countyName = countyElement.select("td").get(1).text();countyVo.setCode(countyCode);countyVo.setName(countyName);countyList.add(countyVo);}cityVo.setChildren(countyList);}cityList.add(cityVo);}areaVo.setChildren(cityList);areaVoList.add(areaVo);System.out.println(areaVo.getName()+":"+gson.toJson(areaVo).toString());}}
}
package com.imant.crawler.vo;import lombok.Data;import java.util.List;@Data
public class AreaVo {private String code;private String name;private List<AreaVo> children;@Overridepublic String toString() {return "AreaVo{" +"code='" + code + '\'' +", name='" + name + '\'' +", children=" + children +'}';}
}
        <!-- https://mvnrepository.com/artifact/org.jsoup/jsoup --><dependency><groupId>org.jsoup</groupId><artifactId>jsoup</artifactId><version>1.11.3</version></dependency><!-- https://mvnrepository.com/artifact/org.projectlombok/lombok --><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>1.18.0</version><scope>provided</scope></dependency><!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 --><dependency><groupId>org.apache.commons</groupId><artifactId>commons-lang3</artifactId><version>3.7</version></dependency><!-- https://mvnrepository.com/artifact/com.google.code.gson/gson --><dependency><groupId>com.google.code.gson</groupId><artifactId>gson</artifactId><version>2.8.5</version></dependency><!-- https://mvnrepository.com/artifact/com.google.guava/guava --><dependency><groupId>com.google.guava</groupId><artifactId>guava</artifactId><version>25.0-jre</version></dependency>

使用Jsoup去国家统计局官网爬取省市县三级json数据相关推荐

  1. Python爬取国家统计局官网最新全国所有城市县镇数据

    最近项目里需要省市区村的数据,网上找了很多方法,都没有如意的,有的老数据竟然还要钱,要积分的我也还认可,我在网上查了下,参考了这位老兄的博客,自己又动手把第五级村级行政加了上去.下面请看大屏幕,我要划 ...

  2. python爬取酷狗音乐json数据为空_【Python3爬虫】下载酷狗音乐上的歌曲

    经过测试,可以下载要付费下载的歌曲(n_n) 准备工作:python3.5+pycharm 使用到的库:requests,re,json 步骤: 打开酷狗音乐的官网,输入想要搜索的歌曲(例如<天 ...

  3. Python3爬取国家统计局官网2017年全国所有城市县镇数据

    最近由于项目需要用到全国城镇乡的数据,网上找了下大部分都是很久之前的,或者不理想的数据,某文库更是无论文章好不好都要下载券,所以索性自己用Python写爬虫爬数据,以下是代码(Python3.6版本) ...

  4. python数据分析图表展示_NBA数据分析_python数据爬取_可视化图形_python数据可视化案例-帆软...

    之前手痒做了一次NBA可视化分析,发个微头条,好多人追着我问教程,这两天终于闲下来了,花时间整理这篇NBA可视化分析教程,手把手教大家做一次炫酷的数据可视化分析! 先部分展示本次教程的作品: 数据获取 ...

  5. Python3爬取国家统计局官网2019年全国所有城市(2020年更新)

    Python3爬取国家统计局官网2019年全国所有城市(2020年更新) 一级城市爬取 一级城市爬取 由于最近需要用到所有城市的数据,故从统计局爬取19年的一级城市数据 import random i ...

  6. 使用python爬取全国所有热门景点数据---去哪儿网

    要爬取去哪儿上面的所有的热门景点的数据 可以先再 搜索出 搜索 热门景点 http://piao.qunar.com/ticket/list.htm?keyword=%E7%83%AD%E9%97%A ...

  7. 程序猿必备福利之二上篇!!!简易使用Nodejs实现从美图网爬取清晰脱俗的美图???

    当然这里为了能够让小白也能够看懂学会,我会说的很详细,我很体谅小白的哦,分了几篇讲解,请谅解哦 这里先来一波看前美图福利,激起你的学习欲望,嘿嘿嘿!!!点击查看程序猿必备福利之二下篇##### 小白如 ...

  8. 如何去使用Python爬虫来爬取B站的弹幕数据?

    哔哩哔哩众所周知是弹幕的天堂,视频观看人数越多,弹幕也就越多.今天小千就来教大家如何去使用Python开发一个爬虫来爬取B站的弹幕数据. 1.弹幕哪里找? 平常我们在看视频时,弹幕是出现在视频上的.实 ...

  9. Python疫起学习·万丈高楼平地起Day09(精简版|浓缩就是精华)爬虫知识附上案例爬取北京地区短租房信息、爬取酷狗TOP500的数据以及爬取网易云音乐热歌榜单

    爬虫知识 Requests库 部分运行结果如下: 有时爬虫需要加入请求头来伪装成浏览器,以便更好地抓取数据.在Chrome浏览器中按F12键打开Chrome开发者工具,刷新网页后找到User-Agen ...

最新文章

  1. Redis 集群部署及踩过的坑
  2. ML基础 : 训练集,验证集,测试集关系及划分 Relation and Devision among training set, validation set and testing set...
  3. PIL:python图像处理库的介绍
  4. WinAPI: PolyBezier - 绘制贝塞尔线
  5. java基础之堆、栈、方法区 继承 多态
  6. 如何设置Windows版Go —快速简便的指南
  7. ioc,di,aop详解
  8. MyISAM的key_buffer_size和InnoDB的innodb_buffer_pool_size
  9. Jquery,Ready函数.
  10. lede旁路由作用_高频旁路电容器作用及工作原理
  11. 2019帝豪gs装软件_继悬浮式车顶之后,2019年这些设计将会成为主流!
  12. nginx-upload-module模块实现文件断点续传
  13. 用计算机计算勾股定理,勾股定理公式计算器(勾股定理计算工具)V2018.1.0 官方版...
  14. 如何从CentOS官网下载我们想要的版本镜像
  15. 西电计算机学院在读博士刘潇,西电版博士研究生学术期刊目录(学科).doc
  16. 【Crystal Reports 水晶报表】奇偶行显示不同的颜色 另附CrystalReports常用属性
  17. 关于removebg官网与API
  18. 开关电源模块 遥控开/关电路
  19. tensorflow streaming_recall@kprecision@k与sklearn的区别
  20. 2022长安杯的网站重构及部分题解

热门文章

  1. JavaCV的摄像头实战之十三:年龄检测
  2. 史上最煽情的博士论文致谢词
  3. 腾讯会议面试-音视频同步问题剖析
  4. 三年已投 1000 亿打造的达摩院,何以仗剑走天涯?
  5. 米格实验室助力医工结合
  6. Sum of Numerators
  7. UCOS你问我答系列之消息邮箱详解
  8. C# winform使用SQLite
  9. 【TT 的魔法猫】Floyd + 剪枝
  10. AndroidStudio 编译中遇到问题总结