使用的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. 阿里巴巴毕玄解密AIOps:一文读懂阿里巴巴运维体系的前世今生

    [编者按]林昊(毕玄),阿里巴巴研发效能事业部负责人.2007年加入阿里,10年间打造了阿里目前使用最为广泛的核心中间件之一的服务框架:建设了阿里的HBase团队,发展到今天HBase已经是阿里最重要 ...

  2. 数据挖掘-diabetes数据集分析-糖尿病病情预测_线性回归_最小平方回归

    # coding: utf-8 # 利用 diabetes数据集来学习线性回归 # diabetes 是一个关于糖尿病的数据集, 该数据集包括442个病人的生理数据及一年以后的病情发展情况. # 数据 ...

  3. Android开发 Camera2开发_2_预览分辨率或拍照分辨率的计算

    前言 不管在Camera1或者Camera2在适配不同手机/不同使用场景的情况下都需要计算摄像头里提供的分辨率列表中最合适的那一个分辨率.所以在需要大量机型适配的app,是不建议不经过计算直接自定义分 ...

  4. 【codeforces 500D】New Year Santa Network

    [题目链接]:http://codeforces.com/problemset/problem/500/D [题意] 有n个节点构成一棵树; 让你随机地选取3个不同的点a,b,c; 然后计算dis(a ...

  5. 深入浅出 Java Concurrency (15): 锁机制 part 10 锁的一些其它问题[转]

    主要谈谈锁的性能以及其它一些理论知识,内容主要的出处是<Java Concurrency in Practice>,结合自己的理解和实际应用对锁机制进行一个小小的总结. 首先需要强调的一点 ...

  6. 深入浅出 Java Concurrency (9): 锁机制 part 4[转]

    本小节介绍锁释放Lock.unlock(). Release/TryRelease unlock操作实际上就调用了AQS的release操作,释放持有的锁. public final boolean ...

  7. gin框架中间件

    1. Gin框架中间件Gin框架中间件A. Gin框架允许在请求处理过程中,加入用户自己的钩子函数.这个钩子函数就叫中间件B. 因此,可以使用中间件处理一些公共业务逻辑,比如耗时统计,日志打印,登陆校 ...

  8. 转:linux驱动开发的经典书籍

    源地址:http://www.cnblogs.com/xmphoenix/archive/2012/03/27/2420044.html Linux驱动学习的最大困惑在于书籍的缺乏,市面上最常见的书为 ...

  9. 使用内部Servlet转发JSP后页面的JS,CSS等资源引入问题的解决

    转载自:https://blog.csdn.net/weixin_44353336/article/details/90677792 问题原因 我们在进行web项目开发过程中,经常会在web页面引入一 ...

  10. Eclipse使用过程的常见问题:

     3-1  "Failed to load the JNI shared library"               -jdk 与eclipse位数不一致出现的问题 解决方法: ...