Python3爬取2023省市区

爬取地址https://www.stats.gov.cn/sj/tjbz/tjyqhdmhcxhfdm/2023/

import re
import requests
import pandas as pd
import warnings
warnings.filterwarnings("ignore")
import time
from lxml import etree
import pymysql
t ,urls ,names = [],[],[]
INDEX_URL = "https://www.stats.gov.cn/sj/tjbz/tjyqhdmhcxhfdm/2023/" #初始url
 # 创建连接
conn = pymysql.connect(host='127.0.0.1',
                       port=3306,
                       user='**',
                       passwd='**', 
                       db='**',
                       charset='utf8mb4')
# 获取游标对象
cursor = conn.cursor()
insert_data_sql = "insert into region(code, name,pcode) values(%s, %s,%s);"
#row = cursor.execute(insert_data_sql, ('shark', 18))

headers = {
    'User-Agent':'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.6) Gecko/20091201 Firefox/3.5.6'
    }
# 创建不验证证书的上下文
# context = ssl.create_default_context()
# context.check_hostname = False
# context.verify_mode = ssl.CERT_NONE
#获取省份页面
#province_response = urllib.request.urlopen(INDEX_URL + "index.html",context=context).read().decode("utf-8")

province_response = requests.get(INDEX_URL + "index.html")
province_response.encoding= 'utf-8'     # 指定编码 
# 获取省份列表
province_data = re.findall(r"<td><a href=\"(.*?)\">(.*?)<br /></a></td>", province_response.text)


def get_city_code(province_url,names,codes):
    # 获取城市初始页
    print(INDEX_URL + province_url)
    print('爬取省份-----------------{}'.format(names))
    global res
 
    try:
        city_response = requests.get(INDEX_URL + province_url)
        city_response.encoding= 'utf-8'     # 指定res的编码 
        #city_response = urllib.request.urlopen(INDEX_URL + province_url,context=context).read().decode("utf-8")
    except Exception as a:
        city_response = requests.get(INDEX_URL + "index.html")
        city_response.encoding= 'utf-8'     # 指定res的编码 
        #city_response = urllib.request.urlopen(INDEX_URL + province_url,context=context).read().decode("utf-8")
        print(a)
 
    # 获取地区名称 + 地区代码
    city_data = etree.HTML(city_response.text) #etree.HTML(city_response)
    for i in city_data.xpath('//tr[@class="citytr"]'):
        code2 = i.xpath('td[1]//text()')[0]
        name2 = i.xpath('td[2]//text()')[0]
        cursor.execute(insert_data_sql, (code2, name2,codes))
        conn.commit()
        try:
            url  = i.xpath('td[1]/a/@href')[0]
            get_area_code(url,code2)
            
        except Exception as a:
            print('异常url:',url)
            print('异常城市:',name2)
            print(f"An error occurred: {a}")
 
 
def get_area_code(city_url,codes):
    # 获取区县
#     print('请求城市',INDEX_URL + city_url)
   
    try:
        area_response = requests.get(INDEX_URL + city_url)
        area_response.encoding= 'utf-8'     # 指定res的编码 
        #area_response = urllib.request.urlopen(INDEX_URL + city_url,context=context).read().decode("utf-8")
#         print('请求成功')
                        
    except Exception as a:     
        area_response = requests.get(INDEX_URL + city_url)
        area_response.encoding= 'utf-8'     # 指定res的编码   
        #area_response = urllib.request.urlopen(INDEX_URL + city_url,context=context).read().decode("utf-8")  #错误后重新调用方法
        
    # 获取街道名称 + 街道代码
    area_data = etree.HTML(area_response.text)
    
    if len(area_data)==0:
        print("---------------------区县异常------------------------------",city_url)
    for i in area_data.xpath('//tr[@class="countytr"]'):
        code3 = i.xpath('td[1]//text()')[0]
        name3 = i.xpath('td[2]//text()')[0]
        cursor.execute(insert_data_sql, (code3, name3,codes))
        
        conn.commit()

 
 
def get_street_code(area_url):
    global res
 
    # 获取街道初始页
    try:
        street_response = requests.get(INDEX_URL + area_url)
        street_response.encoding= 'utf-8'     # 指定res的编码 
        #street_response = urllib.request.urlopen(INDEX_URL + area_url[3:5] + "/" + area_url,context=context).read().decode("utf-8")
    except Exception as a: 
        street_response = requests.get(INDEX_URL + area_url)
        street_response.encoding= 'utf-8'     # 指定res的编码 
        #street_response = urllib.request.urlopen(INDEX_URL + area_url[3:5] + "/" + area_url,context=context).read().decode("utf-8")
        print(a)
 
#     print(street_data)
    street_data = etree.HTML(street_response.text)
    if len(street_data)==0:
        print("---------------------------------------------------",area_url)
    # 获取街道名称 + 街道代码
    for i in street_data.xpath('//tr[@class="towntr"]'):
        code4 = i.xpath('td[1]//text()')[0]
        name4 = i.xpath('td[2]//text()')[0]
        new_row = pd.Series({'代码':code4,'区域':name4})
        res = pd.concat([res,new_row.to_frame() ], ignore_index=True)

for url, name1 in province_data:
    # 获取省份名称 与 代码
    code1 = url.replace(".html", "") + "0" * 10
    if url not in urls:
        
        cursor.execute(insert_data_sql, (code1, name1,0))
        conn.commit()
        get_city_code(url,name1,code1)

     
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: Python3是一种广泛使用的编程语言,它提供了强大的数据处理、网络和数据分析能力。如果需要网页中的表格数据,Python3是一个非常好的选择。 首先,要网页数据,需要使用Python3中的requests和BeautifulSoup模块。requests模块用来发送HTTP请求,获网页源代码,而BeautifulSoup模块用来解析网页数据,从中提所需的信息。 接下来,我们需要找到目标网页中的表格。可以通过使用Chrome浏览器的开发者工具(F12快捷键),在Element选项卡中查找表格的class、id或其他属性信息。 找到表格之后,我们可以使用BeautifulSoup模块中的find_all()方法,根据表格的标签和属性来查找并提表格数据。通过遍历表格中的所有行和列,可以将表格数据保存到一个列表或字典中,方便后续处理和分析。 最后,要注意网络的合法性和道德性。需要遵守网站的规定和协议,不要过度频繁地访问同一网站,不要损害网站的正常运营和用户权益。 总之,使用Python3网页表格是一项非常有价值的技能,能够帮助我们更好地处理和分析网站上的数据,为我们的工作和研究带来更多的便利和效率。 ### 回答2: Python3是一种高级编程语言,具有易读易写的特点,而虫则是利用编程技术获互联网上特定数据的过程,所以Python3非常适合用于网页表格。 网页表格的过程可以分为以下几个步骤: 1.导入所需的python模块:我们需要使用Python中的requests、BeautifulSoup、re、pandas等模块。其中requests模块可用于获网页内容,BeautifulSoup可用于解析网页内容获我们想要的表格,而re和pandas模块则可以将表格内容转化为合适的格式。 2.使用requests.get请求获网页内容。 3.将获的网页内容传给BeautifulSoup进行解析。在这一步中,我们需要找到我们需要的表格所在的HTML标签以及表格内部所需要的各个字段,这些要素都可以用BeautifulSoup来获。 4.设计正则表达式来获表格中所要的数据。 5.使用pandas模块将获到的数据转化为DataFrame格式,处理后可以将其保存为CSV等格式的文件。 总的来说,使用Python3网页表格需要深入了解requests、BeautifulSoup、re、pandas等模块的使用方法,同时也要对HTML语法有一定的了解,才能够高效地解析出所需要的数据,并且能够对数据进行处理和统计分析。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值