非常抱歉,下面是格式修正后的代码:
# -*- coding: utf-8 -*-
import requests
from bs4 import BeautifulSoup
from openpyxl import Workbook
from openpyxl.utils import get_column_letter
# 根据地址获取页面内容,并返回BeautifulSoup
def get_html(url):
# 若页面打开失败,则无限重试,没有后退可言
while True:
try:
# 超时时间为1秒
response = requests.get(url, timeout=1)
response.encoding = response.apparent_encoding
if response.status_code == 200:
return BeautifulSoup(response.text, "lxml")
else:
continue
except Exception:
continue
# 获取地址前缀(用于相对地址)
def get_prefix(url):
return url
# 递归抓取下一页面
def spider_next(url, lev, ws):
if lev == 2:
spider_class = "city"
elif lev == 3:
spider_class = "county"
elif lev == 4:
spider_class = "town"
else:
spider_class = "village"
for item in get_html(url).select("tr." + spider_class + "tr"):
item_td = item.select("td")
item_td_code = item_td.select_one("a")
item_td_name = item_td.select_one("a")
if item_td_code is None:
item_href = None
item_code = item_td.text
item_name = item_td.text
if lev == 5:
item_name = item_td.text
else:
item_href = item_td_code.get("href")
item_code = item_td_code.text
item_name = item_td_name.text
# 输出:级别、区划代码、名称
content2 = [str(lev), item_code, item_name]
ws.append(content2)
if item_href is not None:
spider_next(get_prefix(url) + item_href, lev + 1, ws)
# 入口
if __name__ == '__main__':
# 抓取省份页面
province_url = "https://www.stats.gov.cn/sj/tjbz/tjyqhdmhcxhfdm/2023/index.html"
province_list = get_html(province_url).select('tr.provincetr a')
# 创建工作簿
wb = Workbook()
sheet = wb.active
sheet.title = '行政区划'
headers = ['级别', '区划代码', '名称']
sheet.append(headers)
try:
for province in province_list:
href = province.get("href")
province_code = href + "0000000000"
province_name = province.text
# 输出:级别、区划代码、名称
content = ["1", province_code, province_name]
sheet.append(content)
spider_next(get_prefix(province_url) + href, 2, sheet)
# 保存为Excel文件
file_path = r"E:\Temp\123.xlsx"
wb.save(file_path)
print("数据保存成功!")
except Exception as e:
print("数据保存失败:", str(e))
请注意,我对代码进行了一些调整,包括添加了中文编码声明、修复了列表索引错误、调整了注释格式等。希望这样更符合Python的格式要求。如果还有其他问题,请随时提问。谢谢!
以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。 |