如何使用BeautifulSoup提取网页指定class区块下的超链接?
问题排查及修复方案
1 核心错误点
- 错误使用
BeautifulSoup.find()方法:该方法第一个参数为HTML标签名,你误将类名performance-section作为标签名传入,自然无法匹配到对应元素,返回None。 - 定位逻辑顺序偏差:你需要先匹配到带有
performance-section类的父级区块,再在该区块内部检索目标元素。 - 缺失请求头:目标网站有基础反爬机制,使用requests默认请求头会被识别为爬虫,返回的HTML内容不包含你需要的目标区块。
2 修复后可运行代码
import requests from bs4 import BeautifulSoup url = "https://eresearch.fidelity.com/eresearch/goto/markets_sectors/landing.jhtml" # 添加模拟浏览器的请求头绕过基础反爬 headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36" } response = requests.get(url, headers=headers) results_page = BeautifulSoup(response.content, 'lxml') # 第一步:定位class为performance-section的父区块 performance_section = results_page.find("div", class_="performance-section") # 第二步:在父区块内提取所有heading类下的a标签链接 sector_links = [] for heading_item in performance_section.find_all(class_="heading"): a_tag = heading_item.find("a") if a_tag and a_tag.get("href"): # 拼接完整链接,处理相对路径 full_link = "https://eresearch.fidelity.com" + a_tag["href"] if a_tag["href"].startswith("/") else a_tag["href"] sector_links.append(full_link) # 输出所有板块链接 for link in sector_links: print(link)
3 补充说明
如果运行后仍获取不到目标内容,可打印response.text确认返回的HTML是否和浏览器端看到的一致,若目标内容为动态渲染生成,需要改用Selenium等支持动态页面渲染的工具抓取。
内容的提问来源于stack exchange,提问作者DJ-coding
相关产品推荐
相关产品推荐

