You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 21:09:01