使用的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. 懒散惯了,该收收心了,两天了,封装了一个R0下注册表类

    写得乱七八糟.   看着自己写的代码,感觉都不像自己了.   我写的代码,风格这么差了么?思路这么乱了么?   我写代码这么累么?   不像以前的我了...   这段时间,太懒散了...   该继续努 ...

  2. JS倒计时两种种实现方式 很不错

    最近做浏览器界面倒计时,用js就实现,两种方式: 一:设置时长,进行倒计时.比如考试时间等等 代码如下: <html> <head> <meta charset=&quo ...

  3. sql 递归查询,查出所有子节点

    with t as ( select b.* from Base_Department b where ParentId = 'cce4152c-3483-4334-b68d-155da627bca0 ...

  4. php 网页内容抓取

    最近抓的2个网站内容的代码 列表页抓取:第一种使用phpquery插件,可以快速获取,第二种它是api,所以直接获取 load_third("phpQuery.php"); /** ...

  5. JZOJ P5829 HZOI 20190801 A string 线段树

    JZOJ P5829 A. string 题面:https://www.cnblogs.com/Juve/articles/11286476.html 考场上想起了排序这道题:https://www. ...

  6. 多表关联懒加载导致的org.hibernate.LazyInitializationException: could not initialize proxy - no Session

    本来考虑的是懒加载,这样可以提高效率,不过由于时间紧急 把懒加载改为急加载临时解决 https://www.jianshu.com/p/89520964f458 自己管理session也可以 临时补丁 ...

  7. jsp导出的word默认打开是web视图,希望是页面视图

    方法1 ( velocity+java )我也遇到了这个问题,已经解决:1 .<html xmlns:v='urn:schemas-microsoft-com:vml'xmlns:o='urn: ...

  8. ajax返回后台编译时都对,返回error

    首先看看你的dataType:‘json’  类型是否与后台获取的类型一直.特别是json的格式对不对. 第二: 红括号里的有没有加

  9. 使用Scrapyd部署Scrapy爬虫到远程服务器上

    1.准备好爬虫程序 2.修改项目配置 找到项目配置文件scrapy.cnf,将里面注释掉的url解开来 本代码需要连接数据库,因此需要修改对应的数据库配置 其实就是将里面的数据库地址进行修改,变成远程 ...

  10. 解决CSocket高数据传输问题

    这个是自己项目中发现的问题,所以这个不一定适用于你的. 仅供参考. 头文件: ESSocket.h // ESSocket.h : header file // #ifndef ESSOCKET_H ...