
本文详解如何修正python网络爬虫中因html结构复杂导致的误抓问题,通过定位主内容区域、剔除导航栏干扰项,并确保首条真实新闻链接不被遗漏。
本文详解如何修正python网络爬虫中因html结构复杂导致的误抓问题,通过定位主内容区域、剔除导航栏干扰项,并确保首条真实新闻链接不被遗漏。
在使用 requests + BeautifulSoup 抓取美国卫生与公共服务部(HHS)HIPAA合规协议页面(https://www.php.cn/link/84f9a02942fc8b5734f0a027f59f0a58)时,初版代码常出现两个典型问题:
- 误抓导航栏链接:如 "Resolution Agreements,/hipaa/for-professionals/compliance-enforcement/agreements/index.html" 这类重复首页路径,实为左侧边栏(sidebar)的静态导航项;
- 漏抓首条新闻:真正的第一条协议新闻——“HHS’ Office for Civil Rights Settles Malicious Insider Cybersecurity Investigation for $4.75 Million”——其URL实际指向 /about/news/ 子路径,而非 /agreements/,因此被原过滤条件 "/agreements/" in link_url 直接排除。
根本原因在于:目标内容分散在多个 ✅ 正确做法如下: 以下是优化后的完整可运行代码: ? 注意事项与最佳实践: 通过结构化定位 + 上下文感知筛选,你将稳定获取真实、有序、无噪声的HIPAA合规协议新闻列表——这才是专业级网页抓取应有的精度与鲁棒性。
import requests
from bs4 import BeautifulSoup
import csv
import re
url = "https://www.php.cn/link/84f9a02942fc8b5734f0a027f59f0a58"
response = requests.get(url)
response.raise_for_status() # 确保请求成功
soup = BeautifulSoup(response.text, 'html.parser')
# ✅ 关键修正:只在主内容区域查找链接
content_divs = soup.find_all('div', class_='l-content')
if not content_divs:
raise ValueError("未找到 l-content 容器,请检查页面结构是否变更")
content_div = content_divs[-1] # 取最后一个(即正文区)
links = content_div.find_all('a')
with open('hipaa_resolution_agreements.csv', mode='w', newline='', encoding='utf-8') as file:
writer = csv.writer(file)
writer.writerow(['Title', 'URL'])
for link in links:
link_url = link.get('href')
link_title = link.text.strip()
# ✅ 移除硬路径过滤;增加健壮性判断
if not link_url or not link_title:
continue
if link_url.startswith('#') or link_url.startswith('javascript:'):
continue
# ✅ 可选:清洗标题(移除常见冗余前缀,如日期、编号等)
cleaned_title = re.sub(r'^\d{4}\s*-\s*|\s*\|\s*.*$', '', link_title).strip()
if not cleaned_title: # 清洗后为空则跳过
continue
# 写入CSV
writer.writerow([cleaned_title, link_url])
print("✅ 已成功导出真实协议新闻链接,共写入", len([l for l in links if l.get('href') and l.text.strip()]), "条有效记录。")










