Python爬虫案例-获取最新的中国行政区域划分
源网页:中国统计局标准 http://www.stats.gov.cn/tjsj/tjbz/tjyqhdmhcxhfdm/2016/
打开网页后可以分析出行政区域划分共分为5层

根据传入参数,生成网页地址时需要1-3层的只传本身以及 4层及以后的增加当前省份的前缀。
#生成实际需要解析的页面地址
def geturl(level,url,code):
if level<4:
url=url
else:
url=code[0:2]+'/'+url
url='http://www.stats.gov.cn/tjsj/tjbz/tjyqhdmhcxhfdm/2016/'+url
return url
标签1-5分别不同
#获取需要解析的标签
def getlevelclass(level):
LevelDict={1:"provincetr",2:"citytr",3:"countytr",4:"towntr",5:"villagetr"}
return LevelDict[level]
根据网页上的标签以及实际地址去获取所需要的网页内容
#设置头信息
def getheaders():
headers = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.186 Safari/537.36'}
return headers
#获取网页内容
def Get_WebContent(url,level):
headers=getheaders()
res=urllib.request.Request(url,None, headers=headers)
i=1
while i<4:
try:
response=urllib.request.urlopen(res)
i=100
except error.URLError as e:
print('执行第'+str(i)+'次错误,'+e.reason)
i=i+1
time.sleep(10)
html_content=response.read()
#将html从gb2312编码转换到utf-8的编码
html_content = html_content.decode('gb2312', 'ignore').encode('utf-8')
soup = BeautifulSoup(html_content, 'html.parser', from_encoding='utf-8')
#获得内容
levelclass='.'+getlevelclass(level)
souplist=soup.select(levelclass)
return souplist
根据输出值需要创建解析第一层与其他层的两种函数。
#conding=utf-8
from bs4 import BeautifulSoup #用于解析第二层,内容(Code,Pronvince,urls)
def Get_Child(souplist,parentid,level):
SQLLIST=[]
for provincesoup in souplist:
url_tds=provincesoup.find_all('a',href=True)
a=1
for td in url_tds:
if a%2==1:
code=td.get_text()
urls=td['href']
else:
provience=td.get_text()
row=(code,provience,parentid,level,urls)
SQLLIST.append(row)
a=a+1
return SQLLIST #用于解析第一层,内容(Pronvince,urls),Code=urls中的数字部分
def Get_Main(souplist,parentid,level):
SQLLIST=[]
for provincesoup in souplist:
url_tds=provincesoup.find_all('a',href=True)
for td in url_tds:
provience=td.get_text()
urls=td['href']
code=td['href'].replace('.html', '')
row=(code,provience,parentid,level,urls)
SQLLIST.append(row)
return SQLLIST #实际调用的获取值函数函数
def GetDetail(souplist,level,parentid):
if level==1:
SQLLIST=Get_Main(souplist,parentid,level)
else:
SQLLIST=Get_Child(souplist,parentid,level)
return SQLLIST
SQLSERVER表
CREATE TABLE [dbo].[China_Position](
[ID] [int] IDENTITY(0,1) NOT NULL,
[Code] [nvarchar](20) NULL,
[Name] [nvarchar](40) NULL,
[Name_Short] [nvarchar](20) NULL,
[ParentID] [int] NULL,
[Level] [int] NULL,
[Urls] [nvarchar](200) NULL,
[IsFinish] [smallint] NOT NULL
)
def DataInsert(ValueList):
SQLStr="INSERT INTO [dbo].[China_Position]([Code] ,[Name] ,[ParentID],[Level] ,[Urls]) VALUES(%s ,%s ,%d,%d,%s) "
SqlInsert(SQLStr,ValueList) #获取待运行的任务
def GetTaskList(level):
SQLStr="""SELECT v1.[ID]
,v1.[Level]+1 as [Level]
,v1.[Urls]
,v1.Code
FROM [dbo].[China_Position] v1 with(nolock)
where [IsFinish]=0 And Level=""" + str(level-1)
cur=SqlSelect(SQLStr)
TaskList=[]
for row in cur:
rows=(row[0],row[1],row[2],row[3])
TaskList.append(rows)
return TaskList
#记录执行成功日志
def RecordLog(ID):
SQLStr="update [dbo].[China_Position] set IsFinish=1 where ID="+str(ID)
SqlDelete(SQLStr)
执行最终的代码,获取level1-3层的数据。
for i in range(1,4):
#获取第几层的待执行任务
TaskList=GetTaskList(i)
for CTask in TaskList:
parentid=CTask[0]
level=CTask[1]
url=CTask[2]
Code=CTask[3]
#获取真实的网页
url=geturl(level,url,Code)
#获取网页内容
souplist=Get_WebContent(url,level)
#待插入数据路的列表
ValueList=GetDetail(souplist,level,parentid)
#插入数据库
DataInsert(ValueList)
#记录成功日志,下次执行时不执行已执行的任务
RecordLog(parentid)
Python爬虫案例-获取最新的中国行政区域划分的更多相关文章
- python爬虫--案例分析之针对简单的html文件
python爬虫常用的库:Python 库(urllib.BeautifulSoup.requests.scrapy)实现网页爬虫 python爬虫最简单案例分析: 对一个html文件进行分解,获取 ...
- [Python爬虫] Selenium获取百度百科旅游景点的InfoBox消息盒
前面我讲述过如何通过BeautifulSoup获取维基百科的消息盒,同样可以通过Spider获取网站内容,最近学习了Selenium+Phantomjs后,准备利用它们获取百度百科的旅游景点消息盒(I ...
- python爬虫3——获取审查元素(板野友美吧图片下载)
测试环境:python2.7 + beautifulsoup4.4.1 + selenium2.48.0 测试网址:http://tieba.baidu.com/p/2827883128 目的是下载该 ...
- python 镜像仓库获取最新版本号
#/bin/python# -*- coding: utf-8 -*-import requestsfrom urllib import parsefrom requests.auth import ...
- 【Python爬虫案例】用Python爬取李子柒B站视频数据
一.视频数据结果 今天是2021.12.7号,前几天用python爬取了李子柒的油管评论并做了数据分析,可移步至: https://www.cnblogs.com/mashukui/p/1622025 ...
- 5分钟python爬虫案例,手把手教爬取国内外最新疫情历史数据
俗话说的好,“授之以鱼不如授之以渔”,所以小编今天就把爬疫情历史数据的方法分享给你们. 基本思路:分析腾讯新闻“抗肺炎”版块,采用“倒推法”找到疫情数据接口,然后用python模拟请求,进而保存疫情历 ...
- python爬虫实战 获取豆瓣排名前250的电影信息--基于正则表达式
一.项目目标 爬取豆瓣TOP250电影的评分.评价人数.短评等信息,并在其保存在txt文件中,html解析方式基于正则表达式 二.确定页面内容 爬虫地址:https://movie.douban.co ...
- Python爬虫:获取JS动态内容
经过一段时间的python学习,能写出一些爬虫了.但是,遇到js动态加载的网页就犯了难.于是乎谷歌.百度,发现个好介绍http://www.jianshu.com/p/4fe8bb1ea984 主要就 ...
- 【Python爬虫案例学习】下载某图片网站的所有图集
前言 其实很简短就是利用爬虫的第三方库Requests与BeautifulSoup. 其实就几行代码,但希望没有开发基础的人也能一下子看明白,所以大神请绕行. 基本环境配置 python 版本:2.7 ...
随机推荐
- python在linux中用setproctitle自定义进程名
在linux中,如果想用python自定义进程名,需要用到第三方库setproctitle. #coding:utf8 import setproctitle setproctitle.setproc ...
- java+testng接口测试入门
testNG是一个测试框架,它能组织测试用例按照你想要的方式进行运行,并输出一定格式的便于阅读的测试报告(结果),通过java+testng的方式说明一下接口测试的基本使用方法. 一.环境搭建 a)千 ...
- Springcloud zuul和shiro结合
一.目标1.外部请求统一从网关zuul进入,并且服务内部互相调用接口要校验权限 2.cloud和shiro结合,达到单点登录,和集中一个服务完成权限管理,其他业务服务不需要关注权限如何实现 3.其他服 ...
- iOS CATransition 自定义转场动画
https://www.jianshu.com/p/39c051cfe7dd CATransition CATransition 是CAAnimation的子类(如下图所示),用于控制器和控制器之间的 ...
- WMI Explorer操作 和 powershell命令
powershell查看wmi root 空间 PS C:\Users\yyy> Get-WmiObject -Class __namespace -Namespace root | selec ...
- grep -v 反向查找
grep 是查找含有指定文本行 grep -v 是方向查找,比如 grep -v grep 就是查找 不含有 grep 内容的行,简单来说,就是过滤输入的 grep 命令 Demo: ps -aux ...
- Linux查看用户所属用户组
1.查看当前用户所属用户组 [oracle@serverhl ~]$ groups oinstall dba 2.查看<user1>, <user2> 和 <user3& ...
- CH1201 最大子序和
http://contest-hunter.org:83/contest/0x10%E3%80%8C%E5%9F%BA%E6%9C%AC%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9 ...
- Codeforces 1093D Beautiful Graph(二分图染色+计数)
题目链接:Beautiful Graph 题意:给定一张无向无权图,每个顶点可以赋值1,2,3,现要求相邻节点一奇一偶,求符合要求的图的个数. 题解:由于一奇一偶,需二分图判定,染色.判定失败,直接输 ...
- linux下python安装
下载包: wget https://www.python.org/ftp/python/3.6.3/Python-3.6.3.tar.gz 解压安装: tar -zvxf Python-3.6.3. ...