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

使用BeautifulSoup提取span元素时报ResultSet无find属性如何解决

问题排查与解决方案

核心错误原因

  • 代码缺少requests库的导入语句,直接运行会触发名称错误
  • soup.select()返回的是匹配到的所有元素组成的ResultSet(本质是可迭代列表),仅单个BeautifulSoup元素对象支持find()方法,直接对列表调用该方法就会触发你遇到的报错
  • 原代码中URL被拆分到两行,携带了多余的空格,会导致请求目标地址错误,无法正常获取页面内容

修复方案

方案1:遍历匹配到的td元素查找目标内容

import requests
from bs4 import BeautifulSoup

# 保证URL为完整连续的字符串,不要拆分换行
url = "https://eresearch.fidelity.com/eresearch/markets_sectors/sectors/sectors_in_market.jhtml?tab=learn&sector=25"
response = requests.get(url)
soup = BeautifulSoup(response.content, 'lxml')
td_list = soup.select('div.left-content table.snapshot-data-tbl tr td') 

# 遍历每个td元素查找目标span
for td in td_list:
    target_span = td.find("span", class_='positive')
    if target_span:
        print(target_span.text)
        break

方案2:使用更精准的选择器直接定位(更高效)

直接用select_one()匹配第一个符合规则的元素,不需要分层查找:

import requests
from bs4 import BeautifulSoup

url = "https://eresearch.fidelity.com/eresearch/markets_sectors/sectors/sectors_in_market.jhtml?tab=learn&sector=25"
response = requests.get(url)
soup = BeautifulSoup(response.content, 'lxml')

target = soup.select_one('div.left-content table.snapshot-data-tbl tr td span.positive')
if target:
    print(target.text)

内容的提问来源于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:48:03