晚上好🌙🌙🌙
本答案参考通义千问
当然可以!下面我将为你提供一个完整的 Python 爬虫代码,用于从你提供的安徽省内各市区县的官方网站中爬取招商相关新闻信息,包括:
- 新闻名称
- 地市
- 新闻网址
- 日期
- 人物
- 职务
- 考察地
- 考察企业
- 考察内容或计划合作方向
我们将使用 requests 和 BeautifulSoup 进行网页抓取,并用 pandas 将数据保存为 Excel 表格。
✅ 一、安装依赖库
在运行代码前,请确保你已安装以下 Python 库:
pip install requests beautifulsoup4 pandas openpyxl
✅ 二、Python 完整代码(含详细注释)
import requests
from bs4 import BeautifulSoup
import pandas as pd
import re
from datetime import datetime
# 定义目标网站列表(根据你的需求可扩展)
websites = {
"合肥市政府": "https://hfxz.hefei.gov.cn/xwzx/zwdt/index.html",
"合肥高新区": "https://gxq.hefei.gov.cn/xwdt/yqyw/index.html",
"肥西县": "https://www.ahfeixi.gov.cn/",
"肥东县": "https://www.feidong.gov.cn/index.html",
"长丰县": "https://www.changfeng.gov.cn/index.html",
"包河区": "https://www.baohe.gov.cn/index.html",
"庐江县": "https://www.lj.gov.cn/",
"巢湖市": "https://www.chaohu.gov.cn/",
"合肥市瑶海区": "https://www.hfyaohai.gov.cn/index.html",
"合肥滨湖区": "https://ahchjkq.hefei.gov.cn/index.html",
"淮北市": "https://www.huaibei.gov.cn/index.html",
"亳州市": "https://www.bozhou.gov.cn/",
"宿州市": "https://www.ahsz.gov.cn/",
"蚌埠市": "https://www.bengbu.gov.cn/",
"阜阳市": "https://www.fy.gov.cn/",
"淮南市": "https://www.huainan.gov.cn/",
"滁州市": "https://www.chuzhou.gov.cn/",
"六安市": "https://www.luan.gov.cn/",
"马鞍山市": "https://www.mas.gov.cn/",
"芜湖市": "https://www.wuhu.gov.cn/index.html",
"宣城市": "https://www.xuancheng.gov.cn/",
"铜陵市": "https://www.tl.gov.cn/tlsrmzf/index.html",
"池州市": "https://www.chizhou.gov.cn/News/showList/8/page_1.html",
"安庆市": "https://www.anqing.gov.cn/",
"黄山市": "https://www.huangshan.gov.cn/"
}
# 存储结果的数据结构
data = []
# 遍历每个网站
for city, url in websites.items():
try:
# 发送请求
response = requests.get(url, timeout=10)
response.encoding = 'utf-8' # 设置编码
soup = BeautifulSoup(response.text, 'html.parser')
# 检查是否有新闻列表
news_list = soup.find_all('a', href=re.compile(r'/.*\.html')) # 假设新闻链接以 .html 结尾
for link in news_list[:10]: # 限制爬取数量防止超时
news_url = link.get('href')
if not news_url.startswith('http'):
news_url = f"{url.rstrip('/')}/{news_url}"
# 获取新闻页面内容
try:
news_response = requests.get(news_url, timeout=10)
news_response.encoding = 'utf-8'
news_soup = BeautifulSoup(news_response.text, 'html.parser')
# 提取新闻标题
title_tag = news_soup.find('h1') or news_soup.find('title')
title = title_tag.get_text(strip=True) if title_tag else "无标题"
# 提取日期(根据网站结构调整)
date_tag = news_soup.find('span', class_='date') or news_soup.find('div', class_='time')
date = date_tag.get_text(strip=True) if date_tag else "未知日期"
# 提取正文内容
content = ''
paragraphs = news_soup.find_all(['p', 'div', 'span'])
for p in paragraphs:
content += p.get_text(strip=True) + '\n'
# 使用正则表达式提取关键信息
person_match = re.search(r'([\u4e00-\u9fa5]+)(?:副|厅|局|委|办|长|书记|主任|市长|省长|市长|领导|负责人)', content)
position_match = re.search(r'(副|厅|局|委|办|长|书记|主任|市长|省长|市长|领导|负责人)[\u4e00-\u9fa5]+', content)
place_match = re.search(r'(考察|调研|走访|参观|访问)([\u4e00-\u9fa5]+)', content)
company_match = re.search(r'(企业|公司|园区|项目|基地)([\u4e00-\u9fa5]+)', content)
content_match = re.search(r'(合作|签约|对接|洽谈|推进|推动)([\u4e00-\u9fa5]+)', content)
person = person_match.group(1) if person_match else "未知"
position = position_match.group(1) if position_match else "未知"
place = place_match.group(2) if place_match else "未知"
company = company_match.group(2) if company_match else "未知"
content_info = content_match.group(2) if content_match else "未知"
# 添加到数据中
data.append({
"新闻名称": title,
"地市": city,
"新闻网址": news_url,
"日期": date,
"人物": person,
"职务": position,
"考察地": place,
"考察企业": company,
"考察内容或计划合作方向": content_info
})
except Exception as e:
print(f"解析新闻失败: {news_url}, 错误: {str(e)}")
except Exception as e:
print(f"访问网站失败: {url}, 错误: {str(e)}")
# 保存为Excel文件
df = pd.DataFrame(data)
df.to_excel("安徽招商新闻.xlsx", index=False, engine='openpyxl')
print("✅ 数据已成功保存为 Excel 文件:安徽招商新闻.xlsx")
✅ 三、关键说明与注意事项
1. 网页结构差异
不同网站的 HTML 结构可能不同,上述代码是基于通用模式编写的。如果某些网站无法正确抓取,需要手动分析该网站的 HTML 结构,并调整 find() 或 find_all() 的参数。
2. 反爬机制
部分网站可能有反爬虫机制(如验证码、IP封锁等),建议:
- 使用
headers 模拟浏览器访问 - 使用代理 IP
- 控制请求频率
3. 字段提取逻辑
目前我们使用了正则表达式来提取“人物”、“职务”、“考察地”等字段,但这些字段在不同新闻中的表述方式可能不同,建议后续优化为更智能的自然语言处理(NLP)方法。
✅ 四、优化建议(可选)
| 优化项 | 说明 |
|--------|------|
| 自动识别网站结构 | 使用机器学习模型或规则引擎自动识别不同网站的结构 |
| 多线程/异步请求 | 提高爬取效率 |
| 日志记录 | 记录错误和成功抓取的信息 |
| 定期更新 | 设置定时任务自动抓取最新新闻 |
✅ 五、示例输出表格字段
| 新闻名称 | 地市 | 新闻网址 | 日期 | 人物 | 职务 | 考察地 | 考察企业 | 考察内容或计划合作方向 |
|----------|------|-----------|------|------|------|--------|-----------|-------------------------|
| 某某领导赴北京考察 | 合肥市 | https://... | 2025-04-05 | 张某某 | 副市长 | 北京 | XX科技 | 推进智能制造合作 |
如果你希望我进一步优化代码(例如支持多页爬取、自动识别不同网站结构等),欢迎继续提问!