源网页:中国统计局标准 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爬虫案例-获取最新的中国行政区域划分的更多相关文章

  1. python爬虫--案例分析之针对简单的html文件

    python爬虫常用的库:Python 库(urllib.BeautifulSoup.requests.scrapy)实现网页爬虫 python爬虫最简单案例分析:  对一个html文件进行分解,获取 ...

  2. [Python爬虫] Selenium获取百度百科旅游景点的InfoBox消息盒

    前面我讲述过如何通过BeautifulSoup获取维基百科的消息盒,同样可以通过Spider获取网站内容,最近学习了Selenium+Phantomjs后,准备利用它们获取百度百科的旅游景点消息盒(I ...

  3. python爬虫3——获取审查元素(板野友美吧图片下载)

    测试环境:python2.7 + beautifulsoup4.4.1 + selenium2.48.0 测试网址:http://tieba.baidu.com/p/2827883128 目的是下载该 ...

  4. python 镜像仓库获取最新版本号

    #/bin/python# -*- coding: utf-8 -*-import requestsfrom urllib import parsefrom requests.auth import ...

  5. 【Python爬虫案例】用Python爬取李子柒B站视频数据

    一.视频数据结果 今天是2021.12.7号,前几天用python爬取了李子柒的油管评论并做了数据分析,可移步至: https://www.cnblogs.com/mashukui/p/1622025 ...

  6. 5分钟python爬虫案例,手把手教爬取国内外最新疫情历史数据

    俗话说的好,“授之以鱼不如授之以渔”,所以小编今天就把爬疫情历史数据的方法分享给你们. 基本思路:分析腾讯新闻“抗肺炎”版块,采用“倒推法”找到疫情数据接口,然后用python模拟请求,进而保存疫情历 ...

  7. python爬虫实战 获取豆瓣排名前250的电影信息--基于正则表达式

    一.项目目标 爬取豆瓣TOP250电影的评分.评价人数.短评等信息,并在其保存在txt文件中,html解析方式基于正则表达式 二.确定页面内容 爬虫地址:https://movie.douban.co ...

  8. Python爬虫:获取JS动态内容

    经过一段时间的python学习,能写出一些爬虫了.但是,遇到js动态加载的网页就犯了难.于是乎谷歌.百度,发现个好介绍http://www.jianshu.com/p/4fe8bb1ea984 主要就 ...

  9. 【Python爬虫案例学习】下载某图片网站的所有图集

    前言 其实很简短就是利用爬虫的第三方库Requests与BeautifulSoup. 其实就几行代码,但希望没有开发基础的人也能一下子看明白,所以大神请绕行. 基本环境配置 python 版本:2.7 ...

随机推荐

  1. 查看linux的公网地址

    在搭建环境时,我们需要搭建公网IP地址,因此我们可以使用以下命令查看公网IP地址 curl ifconfig.me 同时我们可以通过以下命令查看公网地址 curl cip.cc

  2. js函数库-D3

    推荐: https://www.cnblogs.com/createGod/p/6884629.html

  3. 一、commander

    #!/usr/bin/env node const program = require('commander'); const colors = require('colors'); const pk ...

  4. HashMap源码解读(jdk1.8)

    1.相关常量 默认初始化容量(大小) static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; 最大容量 static final int M ...

  5. nginx配置https双向验证(ca机构证书+自签证书)

    nginx配置https双向验证 服务端验证(ca机构证书) 客户端验证(服务器自签证书) 本文用的阿里云签发的免费证书实验,下载nginx安装ssl,文件夹有两个文件 这两个文件用于做服务器http ...

  6. Springboot读取Jar文件中的resource

    如题,碰到了问题. 事情是这样的. 一个导入模板, 因为比较少, 所以就直接放在后台的resources中了.调试的时候是下载没有问题的. 等到发布后,下载就出问题了. 参照: ***.jar!\BO ...

  7. iOS NSInteger 的输出 %d %ld %zd %ld (long)

    NSInteger 输出类型 %zd

  8. 微信小程序工具类

    wechat-common-sdk ? 场景:目前工作中的项目需要包含并使用另一个项目. 也许是第三方库,或者你独立开发的,用于多个父项目的库. 现在问题来了:你想要把它们当做两个独立的项目,同时又想 ...

  9. Django内存管理的6种方法

    一.django的缓存方式有6种: 1.开发者调试缓存 2.内存缓存 3.文件缓存 4.数据库缓存 5.Memcache缓存(使用python-memecached模块) 6.Memcache缓存(使 ...

  10. leanote折腾指南

    持续更新. 过几天把自己的修改好的css放到github上给大家参考. https://github.com/whuwangyong/leanote-conf TODO leanote Linux/W ...