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

Selenium find_element报TypeError:'str' object is not callable修复

报错原因
  • 触发TypeError: 'str' object is not callable的直接原因:By.CLASS_NAME是值为"class name"的字符串常量,不是可调用的函数,你写成By.CLASS_NAME('类名')的形式,本质是尝试调用一个字符串,因此抛出类型错误。
  • 你之前尝试find_element(by=By.CLASS_NAME, value=xxx)写法仍然失效的原因:Selenium的CLASS_NAME定位器仅支持传入单个class名,你传入的a-price aok-align-center reinventPricePriceToPayMargin priceToPay是空格分隔的4个独立class组成的复合类属性,不属于单个class名,因此无法匹配到目标元素。
修复方法

改用支持多class匹配的CSS选择器定位,同时修正find_element()的传参格式,定位值使用多class组合的CSS选择器语法(每个class前加.,直接拼接无空格),即可精准匹配到你要的第一个全局唯一的主价格元素。

修正后的可运行代码如下:

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By

service = Service("/Users/myname/Development/chromedriver")
driver = webdriver.Chrome(service=service)

driver.get("https://www.amazon.com/Instant-Pot-Electric-Pressure-One-Touch/dp/B08CF8J3M8/ref=sr_1_10?crid=3HDJU6IJ0LN6Y&keywords=instant+pot+9+in+1+electric+pressure+cooker&qid=1656866250&sprefix=instant+pot+9+in+1+electric+pressure+cooker%2Caps%2C98&sr=8-10")

# 匹配同时携带4个目标class的价格元素,对应页面左侧第一个展示的售价
price = driver.find_element(By.CSS_SELECTOR, '.a-price.aok-align-center.reinventPricePriceToPayMargin.priceToPay')
print(price.text)

driver.quit()

补充说明:运行后打印的文本会按页面渲染格式分行显示货币符号和价格数值,如果需要提取纯浮点型的199.99数值,可对返回的文本做简单的字符串分割、类型转换处理。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 06:15:35