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

使用Selenium提取指定元素内“buy”文本的问题求助

Selenium获取元素文本失败的解决方法

你的代码存在两个关键问题:

  • 未将定位到的Web元素赋值给commentaire变量,直接打印未定义变量会报错
  • 仅定位元素无法直接获取文本,必须调用元素的.text属性

修正后的代码

方式一:通过ID定位

commentaire = browser.find_element_by_id("js-commentaire")
print(commentaire.text.strip())  # strip()可移除文本前后的空格

方式二:通过XPath定位

commentaire = browser.find_element_by_xpath("//*[@id='js-commentaire']")
print(commentaire.text.strip())

额外提示(针对动态加载场景)

如果目标元素是页面动态加载的,建议使用显式等待确保元素加载完成后再操作:

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

# 最长等待10秒,直到元素可见
commentaire = WebDriverWait(browser, 10).until(
    EC.visibility_of_element_located((By.ID, "js-commentaire"))
)
print(commentaire.text.strip())

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 10:25:36