目标网址:http://www.stats.gov.cn/tjsj/tjbz/tjyqhdmhcxhfdm/2016/index.html
爬取所有市级的统计用区划代码和区级、县级的url(即目标网页第二层链接的内容全部爬取),区级、县级及以下的区划代码没有爬取。
网站构造比较简单,容易爬取成功。
import requests from bs4 import BeautifulSoup aimurl="http://www.stats.gov.cn/tjsj/tjbz/tjyqhdmhcxhfdm/2016/index.html"#爬虫目标网址 #输入网址 获得网页的soup def getsoup(url): res=requests.get(url) #以get方法访问目标网址获取网页信息 res.encoding= 'gb2312'#该网页是以gb2312的编码形式显示的 soup=BeautifulSoup(res.text, 'html.parser')#使用美丽汤解析网页内容 return soup #输入一级soup 获得二层网址和省、直辖市的名称 以list存储 def getsecondhtml(soup): secondhtml = [] # 存放二级网址 province = []#存放省、直辖市的名称 for provincetr in soup.select('.provincetr a'):#观察目标网页构造发现想要获取的内容在class provincetr的 a 下 secondhtml.append("http://www.stats.gov.cn/tjsj/tjbz/tjyqhdmhcxhfdm/2016/" + provincetr['href']) province.append(provincetr.text) return secondhtml,province #输入list形式网址,以list获得网址的soup def getlistsoup(listhtml): listsoup = [] for html in listhtml: listsoup.append(getsoup(html)) return listsoup #输入二层列表soup,输出二层统计用区划代码和名称,和第三层的url def gettext2(listsoup2th): text = [] url = [] for soup2 in soup2th: temptext = [] tempurl = []#重复一次 因为统计用区划代码与名称都有链接且是相同的 所以要去除一个 ttempurl = [] for temp in soup2.select('.citytr a'): temptext.append(temp.text) tempurl.append("http://www.stats.gov.cn/tjsj/tjbz/tjyqhdmhcxhfdm/2016/"+temp['href']) text.append(temptext) ttempurl=tempurl[0:-1:2]#去除一个 url.append(ttempurl) return text,url firstsoup = getsoup(aimurl)#获得首页的soup (secondhtml,province)=getsecondhtml(firstsoup)#获得第二层市级的html和省直辖市名称 soup2th=getlistsoup(secondhtml)#获得第二层市级统计用区划代码的soup (text2,url3)=gettext2(soup2th)#获得第二层市级统计用区划代码与名称和第三层的url
结果展示代码(初学python 写的很烂):
for i,j,p in zip(province,text2,url3): print(i) n=0 flag=0 for k in j: flag=flag+1 print(k,end=' ') if flag==2: flag=0 print(p[n]) n=n+1 print()
输出结果:
北京市
110100000000 市辖区 http://www.stats.gov.cn/tjsj/tjbz/tjyqhdmhcxhfdm/2016/11/1101.html
天津市
120100000000 市辖区 http://www.stats.gov.cn/tjsj/tjbz/tjyqhdmhcxhfdm/2016/12/1201.html
河北省
130100000000 石家庄市 http://www.stats.gov.cn/tjsj/tjbz/tjyqhdmhcxhfdm/2016/13/1301.html
130200000000 唐山市 http://www.stats.gov.cn/tjsj/tjbz/tjyqhdmhcxhfdm/2016/13/1302.html
130300000000 秦皇岛市 http://www.stats.gov.cn/tjsj/tjbz/tjyqhdmhcxhfdm/2016/13/1303.html
130400000000 邯郸市 http://www.stats.gov.cn/tjsj/tjbz/tjyqhdmhcxhfdm/2016/13/1304.html
130500000000 邢台市 http://www.stats.gov.cn/tjsj/tjbz/tjyqhdmhcxhfdm/2016/13/1305.html
130600000000 保定市 http://www.stats.gov.cn/tjsj/tjbz/tjyqhdmhcxhfdm/2016/13/1306.html
130700000000 张家口市 http://www.stats.gov.cn/tjsj/tjbz/tjyqhdmhcxhfdm/2016/13/1307.html
130800000000 承德市 http://www.stats.gov.cn/tjsj/tjbz/tjyqhdmhcxhfdm/2016/13/1308.html
130900000000 沧州市 http://www.stats.gov.cn/tjsj/tjbz/tjyqhdmhcxhfdm/2016/13/1309.html
131000000000 廊坊市 http://www.stats.gov.cn/tjsj/tjbz/tjyqhdmhcxhfdm/2016/13/1310.html
131100000000 衡水市 http://www.stats.gov.cn/tjsj/tjbz/tjyqhdmhcxhfdm/2016/13/1311.html
139000000000 省直辖县级行政区划 http://www.stats.gov.cn/tjsj/tjbz/tjyqhdmhcxhfdm/2016/13/1390.html