使用的python3.6

民政网站,不同年份数据可能页面结构不一致,这点踩了很多坑,这也是代码越写越长的原因。

如果以后此段代码不可用,希望再仔细学习下 页面结构是否发生了变更。

 # -*- coding: utf-8 -*-
"""
Created on Wed Jul 10 14:40:41 2019 @author: Administrator
""" import pandas as pd
import requests
from bs4 import BeautifulSoup
import time url1 = 'http://www.mca.gov.cn/article/sj/xzqh//1980/'
headers = {'content-type': 'application/json',
'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:22.0) Gecko/20100101 Firefox/22.0'} # 1. 获取所有链接========================================================================
def f1(url1):
'2018-1980年中华人民共和国行政区划代码 的所有链接'
#requests发出请求,设置url,header参数
response = requests.get(url1, headers=headers, timeout=200, verify=False)
soup = BeautifulSoup(response.text,'lxml') #将网页源码返回为BeautifulSoup类型
_tmp1 = soup.select('td.arlisttd')
end_1 = []
for i in _tmp1:
_a = i.select('a')[0].get('href')
_b = i.select('a')[0].get('title')[:4]
end_1.append(['http://www.mca.gov.cn'+_a,_b])
return end_1 end_2=[]
for i in ['','?2','?3']:
end_2 = end_2+f1(url1+i) def f2(url1='http://www.mca.gov.cn/article/sj/xzqh/2019/'):
'2019年中华人民共和国行政区划代码'
response = requests.get(url1, headers=headers, timeout=200, verify=False)
soup = BeautifulSoup(response.text,'lxml')
_tmp1 = soup.select('td.arlisttd')
end_1 = []
for i in _tmp1:
_a = i.select('a')[0].get('href')
_b = i.select('a')[0].get('title')[:7]
end_1.append(['http://www.mca.gov.cn'+_a,_b])
return end_1 end_2 = end_2+f2() # 2. 获取数据========================================================================
def f3(url1='http://www.mca.gov.cn/article/sj/xzqh/1980/201903/20190300014989.shtml'):
#url1='http://www.mca.gov.cn/article/sj/xzqh/1980/201507/20150715854922.shtml'
#url1='http://www.mca.gov.cn/article/sj/xzqh/1980/201507/20150715854918.shtml'
#
response = requests.get(url1, headers=headers, timeout=200, verify=False)
soup = BeautifulSoup(response.text,'lxml')
_txt = soup.select('script')[4].get_text().strip().replace('window.location.href="','').strip('";')
if _txt[-4:]=='html':
print('script!')
url2 = _txt
else:
_tmp1 = soup.select('div.artext > div > p > a')
if len(_tmp1)==0:
_tmp1 = soup.select('div#zoom > a')
url2 = _tmp1[0].get('href')
print(url2)
#return url2
#url2='http://www.mca.gov.cn/article/sj/tjbz/a/201713/201708220856.html'
time.sleep(0.5)
response = requests.get(url2, headers=headers, timeout=200, verify=False)
#将网页源码返回为BeautifulSoup类型
soup = BeautifulSoup(response.text,'lxml')
_tmp1 = soup.select('table > tr[height="19"]')
end_1 = []
if len(_tmp1)>5:
for i in _tmp1:
_a = i.select('td')[1].get_text().strip()
if len(_a)>15: #部分数据页面,最后一行是备注。
continue
else:
_b = i.select('td')[2].get_text().strip()
end_1.append([_a,_b])
else:
_tmp1 = soup.select('table > tr[height="20"]')
for i in _tmp1:
_a = i.select('td')[0].get_text().strip()
if len(_a)>15 or _a=='行政区划代码': #部分数据页面,最后一行是备注。
continue
else:
_b = i.select('td')[1].get_text().strip()
end_1.append([_a,_b]) return end_1 #循环对每个链接 获取数据
end_3=[];#end_4=[]
for j in range(len(end_2)):
item = end_2[j]
if '' in item[1] or '' in item[1]:
print(j,item[0],item[1])
tmp2 = f3(item[0])
print('.')
end_3.extend([[item[1]]+i for i in tmp2])
#end_4.append(tmp2)
time.sleep(0.1) df_result = pd.DataFrame(end_3)
#pd.DataFrame(end_4).to_excel('所有连接.xlsx',index=False)
df_result.to_excel('地区编码.xlsx',index=False) '''
#\3 2019年5月份县以上行政区划代码_3852 > table > tbody > tr:nth-child(4)
#list_content > div.list_right > div > ul > table > tbody > tr:nth-child(1) > td.arlisttd > a
'''

使用python爬去国家民政最新的省份代码的程序,requests,beautifulsoup,lxml的更多相关文章

  1. Python逐块读取大文件行数的代码 - 为程序员服务

    Python逐块读取大文件行数的代码 - 为程序员服务 python数文件行数最简单的方法是使用enumerate方法,但是如果文件很大的话,这个方法就有点慢了,我们可以逐块的读取文件的内容,然后按块 ...

  2. python爬去电影天堂恐怖片+游戏

    1.爬去方式python+selenium 2.工作流程 selenium自动输入,自动爬取,建立文件夹,存入磁力链接到记事本 3.贴上代码 #!/usr/bin/Python# -*- coding ...

  3. 【Python】在Pycharm中安装爬虫库requests , BeautifulSoup , lxml 的解决方法

    BeautifulSoup在学习Python过程中可能需要用到一些爬虫库 例如:requests BeautifulSoup和lxml库 前面的两个库,用Pychram都可以通过 File--> ...

  4. Python爬去图片实例,python 爬取图片

    # coding:utf-8 import requests import re import time proxies = { "http": "http://124. ...

  5. Python爬去有道翻译

    注:传入的类型为POST类型,所以需要使用urllib.parse.urlencode(),将字典转换成URL可用参数: 使用json.loads(),将输出的json格式,转换为字典类型 impor ...

  6. 利用Python爬去囧网福利(多线程、urllib、request)

    import os; import urllib.request; import re; import threading;# 多线程 from urllib.error import URLErro ...

  7. python爬去虎扑数据信息,完成可视化

    首先分析虎扑页面数据 如图我们所有需要的数据都在其中![image.png](1)所以我们获取需要的内容直接利用beaitifulsoupui4``` soup.find_all('a',class_ ...

  8. python爬去壁纸网站上的所有壁纸

    import requests as r 2 from bs4 import BeautifulSoup 3 import os 4 base_url = "http://www.win40 ...

  9. python爬微信公众号前10篇历史文章(3)-lxml&xpath初探

    理解lxml以及xpath 什么是lxml? python中用来处理XML和HTML的library.与其他相比,它能提供很好的性能, 并且它支持XPath. 具体可以查看官方文档->http: ...

随机推荐

  1. <每日一题>题目16:简单的python练习题(1-10)

    #1.python程序中__name__的作用是什么? __name__这个系统变量用来表示程序的运行方式. 如果程序在当前膜快运行,__name__的名称就是__main__, 如果不在(被调用), ...

  2. .Net Core微服务系列--服务发现

    什么是服务发现 首先我们先思考一个问题,当我们在浏览器中输入一个域名比如baidu.com,然后发生了什么才能让我们访问到百度的网页?简单来说,浏览器会首先从主机的hosts文件中查看是否有baidu ...

  3. 短URL系统、301/302重定向

    短 URL 系统是怎么设计的?https://yq.aliyun.com/articles/87600 短网址(short URL)系统的原理及其实现 https://hufangyun.com/20 ...

  4. vue-cli 构建项目

    1.安装vue-cli和webpack npm install webpack -g npm install vue-cli -g 2.vue-cli初始化项目 vue init webpack-si ...

  5. 跟我一起学习webpack(一)

    跟我一起打包我们的第一个应用 第一步安装webpack 接下来我们新建文件 //add-content.js export default function(){ document.write('he ...

  6. python中defaultdict方法的使用

    默认值可以很方便 众所周知,在Python中如果访问字典中不存在的键,会引发KeyError异常(JavaScript中如果对象中不存在某个属性,则返回undefined).但是有时候,字典中的每个键 ...

  7. $cordovaNetwork 使用

    1 .安装插件 直接安装: cordova plugin add cordova-plugin-network-information 下载到本地安装: https://github.com/apac ...

  8. LUOGU P1965 转圈游戏 (Noip 2013)

    传送门 解题思路 比较简单的模拟题,转圈一定有一个循环节,而且循环节长度一定小于m,因为循环节是一个%m的剩余系,然后一遍模拟记录下来循环节,快速幂即可. #include<iostream&g ...

  9. C++继承相关知识点总结

    1:派生类继承基类的成员并且可以定义自己的附加成员.每个派生类对象包含两个部分:从基类继承的成员和自己定义的成员. 每个派生类对象都有基类部分,包括基类的private成员.类可以访问共基类的publ ...

  10. 循环/闭包/setTimeout/Promise 综合

    控制台显示内容为? for (var i = 0; i < 5; i++) { console.log(i); } 控制台显示内容为? for (var i = 0; i < 5; i++ ...