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

使用Selenium追踪实时股价时遇TypeError: 'str' object is not callable报错求助

问题解决:Selenium TypeError: 'str' object is not callable

错误原因

你调用driver.find_element()的方式有误:

  • Selenium 4 中driver.find_element()需要两个独立参数:定位策略(如By.XPATH)和定位表达式字符串。
  • 你错误地将By.XPATH当作函数调用(写成By.XPATH('xxx')),但By.XPATH本质是字符串常量(值为"xpath"),并非可调用函数,因此触发TypeError。

修正方案

1. 修复定位代码

把出错的行改为正确的参数传递方式:

price_info = driver.find_element(By.XPATH, '/html/body/section/div[1]/div[1]/div[3]/div/div[1]/div[1]/div[2]/div[1]/div')

2. 优化定位稳定性(推荐)

绝对XPath依赖页面层级结构,页面更新后很容易失效,建议改用更稳定的相对定位方式:

  • 示例1:通过类名定位(需先查看元素实际class,比如页面中价格元素的class为last-price)
price_info = driver.find_element(By.CLASS_NAME, 'last-price')
  • 示例2:通过相对XPath定位
price_info = driver.find_element(By.XPATH, '//div[contains(@class, "last-price")]')

完整可运行代码

from selenium import webdriver
from selenium.webdriver.common.by import By
from time import sleep

options = webdriver.ChromeOptions()
options.add_experimental_option('excludeSwitches', ['enable-logging'])
driver = webdriver.Chrome(options=options)
driver.maximize_window()
driver.delete_all_cookies()
driver.get("https://finans.mynet.com/borsa/hisseler/asels-aselsan/")
driver.implicitly_wait(5)

# 修正后的定位,这里用相对XPath示例
price_info = driver.find_element(By.XPATH, '//div[contains(@class, "last-price")]')
print(f"初始价格: {price_info.text}")

# 实时追踪价格
try:
    while True:
        current_price = driver.find_element(By.XPATH, '//div[contains(@class, "last-price")]').text
        print(f"当前价格: {current_price}")
        sleep(5)  # 每5秒刷新一次
except KeyboardInterrupt:
    driver.quit()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 02:10:51