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

如何使用Selenium WebDriver获取指定class的元素文本内容?

正确实现方案

错误原因

  • 代码中content是WebElement对象,直接和整数24对比永远不成立,需提取元素文本并转整数后再对比
  • 所用find_element_by_xpath、executable_path、chrome_options是Selenium 3.x旧API,4.x版本已废弃,会触发报错
  • 无元素等待逻辑,页面未加载完成时会抛出元素不存在异常

修正后代码(适配Selenium 4.x)

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

options = webdriver.ChromeOptions()
options.add_argument(r"--user-data-dir=C:\Users\bji\AppData\Local\Google\Chrome\User Data")
options.add_argument(r'--profile-directory=Default')
s = Service(r'C:\Users\bji\Downloads\chromedriver_win32(1)\chromedriver.exe')
driver = webdriver.Chrome(service=s, options=options)

driver.get('wanted website')

# 最长等待10秒加载目标元素
wait = WebDriverWait(driver, 10)
content_ele = wait.until(EC.presence_of_element_located((By.XPATH, '//*[@id="__layout"]/div/div[2]/div[1]/div[1]/div/div[2]/ul/li[1]/a/div[3]/div[2]/div/p')))

# 提取文本去空转整数后判断
if int(content_ele.text.strip()) == 24:
    content_ele.click()

Selenium 3.x版本仅需修改判断逻辑

# 原有代码不变,仅替换判断部分
content = driver.find_element_by_xpath('//*[@id="__layout"]/div/div[2]/div[1]/div[1]/div/div[2]/ul/li[1]/a/div[3]/div[2]/div/p')
if int(content.text.strip()) == 24:
    content.click()

优化建议

  • 原XPath为绝对路径,页面结构变动即失效,建议用class属性定位更稳定://p[contains(@class,"text__green") and text()="24"]
  • 元素文本可能存在空格、换行,用strip()去除后再对比可降低误判概率

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 11:36:03