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

# -*- coding: utf-8 -*-
# author:zjp"""
通过国家统计局官网获取中国2018年所有城市数据
http://www.stats.gov.cn/tjsj/tjbz/tjyqhdmhcxhfdm/2017/
"""
import re
import requests
import time
import sysfileSavePath = 'F://data/China_Province_2018.txt'  # 数据储存路径
fileSavePath2 = 'F://data/China_Province_2018_mistake.txt'  # 错误信息储存路径
results2 = []
results3 = []
results4 = []
results5 = []
Dates1 = []n = 0
# 获取一级城市信息
url = 'http://www.stats.gov.cn/tjsj/tjbz/tjyqhdmhcxhfdm/2018/index.html'
response = requests.get(url)
response.raise_for_status()  # 如果 HTTP 请求返回了不成功的状态码,Response.raise_for_status() 会抛出一个 HTTPError异常
response.encoding = response.apparent_encoding  # response.apparent_encoding从内容中分析出的响应内容编码方式
pattern = re.compile("<a href='(.*?)'>(.*?)<")
result1 = list(set(re.findall(pattern, response.text)))  # 从首层页面获取进入第二层页面的html
#print('result1')
#print(result1)# 从一级城市获取二级城市信息
for cycle1 in range(len(result1)):try:url1 = 'http://www.stats.gov.cn/tjsj/tjbz/tjyqhdmhcxhfdm/2018/{0}'.format(result1[cycle1][0])  # 一级城市urladdress1 = result1[cycle1][1]   # 一级城市#print('{0}  {1}'.format(address1, url1))response1 = requests.get(url1)response1.raise_for_status()response1.encoding = response1.apparent_encodingresponse1.close()pattern1 = re.compile("<a href='(.*?)'>(.*?)<")  # 正则表达式提取目标字段result2_1 = list(set(re.findall(pattern1, response1.text)))result2 = []for result in result2_1:  # 爬取的城市信息和城市代码混在一起,需要将代码清除if '0' not in result[1]:result2.append(result)#print('result2')#print(result2)except:print("Unexpected error:", sys.exc_info())with open(fileSavePath, 'a', encoding='utf-8')as f:f.write('{0}|一级错误|一级错误|一级错误|{1}\n'.format('xd', sys.exc_info()))f.close()time.sleep(10)continue# 从二级城市获取三级城市信息for cycle2 in range(len(result2)):try:address2 = result2[cycle2][1]  # 二级城市url2 = 'http://www.stats.gov.cn/tjsj/tjbz/tjyqhdmhcxhfdm/2018/{0}'.format(result2[cycle2][0])  # 二级城市url#print(url2)response2 = requests.get(url2)response2.raise_for_status()response2.encoding = response2.apparent_encodingresponse2.close()pattern2 = re.compile("<a href='(.*?)'>(.*?)<")result3_1 = list(set(re.findall(pattern2, response2.text)))result3 = []for result in result3_1:if '0' not in result[1]:result3.append(result)#print('result3')#print(result3)except:print("Unexpected error:", sys.exc_info())with open(fileSavePath, 'a', encoding='utf-8') as f:f.write('{0}|二级错误|二级错误|二级错误|{1}\n'.format(address1, sys.exc_info()))f.close()time.sleep(10)continue# 从三级城市获取四级城市信息for cycle3 in range(len(result3)):try:address3 = result3[cycle3][1]  # 三级城市url3 = 'http://www.stats.gov.cn/tjsj/tjbz/tjyqhdmhcxhfdm/2018/{0}/{1}'\.format(result3[cycle3][0][3:5], result3[cycle3][0])   # 三级城市urlresponse3 = requests.get(url3)response3.raise_for_status()response3.encoding = response3.apparent_encodingresponse3.close()pattern3 = re.compile("<a href='(.*?)'>(.*?)<")result4_1 = list(set(re.findall(pattern3, response3.text)))result4 = []for result in result4_1:if '0' not in result[1]:result4.append(result)#print('result4')#print(result4)except:print("Unexpected error:", sys.exc_info())with open(fileSavePath, 'a', encoding='utf-8')as f:f.write('{0}|三级错误|三级错误|三级错误|{1}\n'.format(address2, sys.exc_info()))f.close()time.sleep(10)continue# 从四级城市获取四五级城市信息for cycle4 in range(len(result4)):try:address4 = result4[cycle4][1]  # 四级城市url4 = 'http://www.stats.gov.cn/tjsj/tjbz/tjyqhdmhcxhfdm/2017/{0}/{1}/{2}'\.format(result4[cycle4][0][3:5], result4[cycle4][0][5:7], result4[cycle4][0])  # 四级城市urlresponse4 = requests.get(url4)response4.raise_for_status()response4.encoding = response4.apparent_encodingresponse4.close()time.sleep(1)pattern4_1 = re.compile("<a href='(.*?)'>(.*?)<")# 可能已经到最后一层pattern4 = re.compile("<tr class='villagetr'><td>.*?</td><td>.*?</td><td>(.*?)</td></tr>")result5_1 = list(set(re.findall(pattern4, response4.text)))result5 = []for result in result5_1:if '0' not in result[1]:result5.append(result)print('result5')print(result5)if result5:for cycle5 in result5:address = '{0}|{1}|{2}|{3}|{4}'.format(address1, address2, address3, address4, cycle5)print(address)with open(fileSavePath, 'a', encoding='utf-8')as f:f.write(address)f.write('\n')f.close()else:print('此处第五层城市结果为空,网址为: {0}'.format(url4))with open(fileSavePath2, 'a', encoding='utf-8')as f2:f2.write('此处第五层城市结果为空,网址为: {0}'.format(url4))f2.close()except:print("Unexpected error:", sys.exc_info())with open(fileSavePath, 'a', encoding='utf-8')as f:f.write('{0}|四级错误|四级错误|四级错误|{1}\n'.format(address3, sys.exc_info()))f.close()time.sleep(10)continue
print('well_done')

这是部分爬取结果:

安徽省|马鞍山市|和县|功桥镇|鲁堡村委会
安徽省|马鞍山市|和县|功桥镇|丰山村委会
安徽省|马鞍山市|和县|功桥镇|东堡村委会
安徽省|马鞍山市|和县|功桥镇|考塘村委会
安徽省|马鞍山市|和县|功桥镇|毛巷村委会
安徽省|马鞍山市|和县|功桥镇|杨圩村委会
安徽省|马鞍山市|和县|功桥镇|新塘村委会
安徽省|马鞍山市|和县|功桥镇|功桥社区居委会
安徽省|马鞍山市|和县|功桥镇|南义社区居委会
安徽省|马鞍山市|和县|功桥镇|长建村委会
安徽省|马鞍山市|和县|功桥镇|大汤圩村委会
安徽省|马鞍山市|和县|白桥镇|白桥街社区居委会
安徽省|马鞍山市|和县|白桥镇|周贵仕村委会
安徽省|马鞍山市|和县|白桥镇|后港社区居委会
安徽省|马鞍山市|和县|白桥镇|红旗村委会
安徽省|马鞍山市|和县|白桥镇|西梁山村委会
安徽省|马鞍山市|和县|白桥镇|兴隆村委会
安徽省|马鞍山市|和县|白桥镇|徐庄村委会
安徽省|马鞍山市|和县|白桥镇|陈桥洲村委会

数据量有点大,爬取时间很长,有需要的(懒得爬的朋友)可以联系我,我可以提供爬取到的数据集。

如有疑问请联系我,欢迎骚扰:

Python3爬取国家统计局官网2017年全国所有城市县镇数据相关推荐

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

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

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

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

  3. 用python输出所有的玫瑰花数_用Python爬取WordPress官网所有插件

    转自丘壑博客,转载注明出处 前言 只要是用WordPress的人或多或少都会装几个插件,可以用来丰富扩展WordPress的各种功能.围绕WordPress平台的插件和主题已经建立了一个独特的经济生态 ...

  4. python爬取千图网_python爬取lol官网英雄图片代码

    python爬取lol官网英雄图片代码可以帮助用户对英雄联盟官网平台的皮肤图片进行抓取,有很多喜欢lol的玩家们想要官方的英雄图片当作自己的背景或者头像,可以使用这款软件为你爬取图片资源,操作很简单, ...

  5. 如何用Python爬取LOL官网全英雄皮肤

    今天小编带你爬取LOL官网全英雄皮肤的图片 不要失望,也不要难过 接下咱们来讲讲怎么爬取LOL官网 本次案例使用到的模块 import requests import re import json 安 ...

  6. 爬虫实战(二)—利用requests、selenium爬取王者官网、王者营地APP数据及pymongo详解

    概述 可关注微信订阅号 loak 查看实际效果. 代码已托管github,地址为:https://github.com/luozhengszj/LOLGokSpider ,包括了项目的所有代码. 本文 ...

  7. python爬虫入门练习,使用正则表达式和requests爬取LOL官网皮肤

    刚刚python入门,学会了requests模块爬取简单网页,然后写了个爬取LOL官网皮肤的爬虫,代码奉上 #获取json文件 #获取英雄ID列表 #拼接URL #下载皮肤 #导入re request ...

  8. websect爬取小米官网数据

    webesct 首先要下载webesct nom i websect 老规矩,还是爬取小米官网的数据QAQ,现在要爬取的是这个: const $ = require("websect&quo ...

  9. python使用selenium爬取联想官网驱动(一):获取遍历各驱动的下载网址

    python使用selenium爬取联想官网驱动(一):获取遍历各驱动的下载网址然后wget命令试验下载 由于初期学习,所以先拿一个型号的产品驱动试验. (1)以下为在联想某型号产品获取相关驱动下载的 ...

最新文章

  1. 吕乐:医学影像学者的医者仁心 | 智源专访
  2. poj - 3786 Repeater
  3. 浅析SEO优化怎样打好企业新站优化基础稳步提升排名
  4. 计划订单号码范围用完导致MRP无法运行
  5. java 怎么获取形参名_获得方法形参名称列表 -- 哦也,搞定!!
  6. vue 修改标题栏_VUE动态修改titile的三种方法
  7. 3 WM配置-主数据-定义仓库编号的控制参数
  8. 又搞事!雷军郑重宣告:小米9才是骁龙855全球真首发
  9. springboot中mongodb自定义类型转换器
  10. mininet的安装
  11. 【工具推荐】免费的思维导图软件——Blumind
  12. vue transition淡入淡出
  13. 中国各地旅游五十项注意,请大家谨记
  14. 用计算机时的注意事项,计算机使用注意事项
  15. linux网络入侵命令,如何使用netstat命令验证DDOS入侵
  16. ETF操作实战记录:2022-2-22
  17. buuctf 派大星的烦恼 详解
  18. MySQL——数据库读写分离原理
  19. 第一次软件工程作业--心理测试系统
  20. win11和win10哪个好 win11和win10对比分析

热门文章

  1. ubuntu qt平台搭建openssl开发环境
  2. 通信电子电路(一)通电课程背景 以及选频网络概念
  3. IntelliJ Idea -- 自动引包设置
  4. 洛谷P1004方格取数
  5. java将分钟转为小时
  6. 数字油田AI平台建设之视野、策略及切入点(深度好文)
  7. ImportError: (‘You must install pydot (`pip install pydot`) and install grap
  8. PAT甲级刷题笔记(4)
  9. 教师专业发展规划计算机教师,初中信息技术教师个人发展计划
  10. iOS 加载、滑动翻阅大量图片解决方案详解