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

使用BeautifulSoup网页爬取报错:TypeError: 'ResultSet'对象不可调用

网页爬取报错:TypeError: 'ResultSet' object is not callable

问题代码

import requests
from bs4 import BeautifulSoup

url='https://finance.yahoo.com/quote/AAPL'

response = requests.get(url)
soup = BeautifulSoup(response.text, 'lxml')

price = soup.find_all('div', {'class' : 'My(6px) Pos(r) smartphone_Mt(6px)'})(0).find()
print(price)

报错信息

TypeError                                 Traceback (most recent call last)
<ipython-input-23-4a9fd9081b7f> in <module>
      8 #print(soup)
      9 
---> 10 price = soup.find_all('div', {'class' : 'My(6px) Pos(r) smartphone_Mt(6px)'})(0).find()
     11 print(price)

TypeError: 'ResultSet' object is not callable

错误原因

soup.find_all()返回的是ResultSet对象(本质是元素列表),你用圆括号(0)去调用这个对象属于语法错误——列表/ResultSet取元素必须用方括号[0],圆括号仅用于调用可执行的函数或方法,而ResultSet不是可调用对象,因此触发该错误。

解决方法

方法1:改用find()(推荐)

如果只需要第一个匹配的元素,直接用soup.find()更高效,它直接返回单个元素,无需额外索引:

import requests
from bs4 import BeautifulSoup

url='https://finance.yahoo.com/quote/AAPL'

response = requests.get(url)
soup = BeautifulSoup(response.text, 'lxml')

price = soup.find('div', {'class' : 'My(6px) Pos(r) smartphone_Mt(6px)'}).find()
print(price)

方法2:修正find_all()的索引方式

如果坚持用find_all(),把圆括号(0)改为方括号[0]即可:

import requests
from bs4 import BeautifulSoup

url='https://finance.yahoo.com/quote/AAPL'

response = requests.get(url)
soup = BeautifulSoup(response.text, 'lxml')

price = soup.find_all('div', {'class' : 'My(6px) Pos(r) smartphone_Mt(6px)'})[0].find()
print(price)

额外建议:避免索引越界

find_all()可能返回空列表,直接取[0]会触发IndexError,建议先判断是否有匹配结果:

import requests
from bs4 import BeautifulSoup

url='https://finance.yahoo.com/quote/AAPL'

response = requests.get(url)
soup = BeautifulSoup(response.text, 'lxml')

target_divs = soup.find_all('div', {'class' : 'My(6px) Pos(r) smartphone_Mt(6px)'})
if target_divs:
    price = target_divs[0].find()
    print(price)
else:
    print("未找到目标div元素")

内容的提问来源于stack exchange,提问作者HeTheresa

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 11:01:04