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

Selenium报错AttributeError: 'str' object has no attribute 'text'如何解决

错误原因
  • 你执行driver.find_element_by_id('com.project.PROJECT:id/version').text后,已经把Selenium WebElement对象的文本内容提取为字符串,赋值给version变量后,version本身就是字符串类型,不存在text属性。
  • 对字符串执行for i in version遍历操作时,每次取出的i是字符串中的单个字符,拿单个字符和完整的版本号字符串对比,永远不可能匹配成功,所以一直输出失败结果。
  • 后续尝试调用i.text时,i是字符串类型的单个字符,本身没有text属性,直接触发AttributeError: 'str' object has no attribute 'text'报错。
解决方案

场景1:当前ID仅匹配一个版本元素(你当前代码的场景)

你不需要遍历字符串,直接对比提取到的文本即可,代码修正如下:

# 提取元素文本为字符串
version = driver.find_element_by_id('com.project.PROJECT:id/version').text
print(version)
# 直接对比文本,strip()用于去除前后多余空格、换行符,避免匹配失败
if version.strip() == 'Version : 1.2.0.133':
    print('Step 46. NAS version is displayed correctly - PASS')
else:
    print('Step 46. NAS version is incorrect - Fail')
time.sleep(2)

场景2:你需要匹配多个同ID的版本元素

如果你的需求是遍历多个版本元素匹配内容,不要在获取元素时就调用.text,先获取元素列表再遍历取文本:

# 用find_elements获取所有匹配的元素,不提前调用.text
version_elements = driver.find_elements_by_id('com.project.PROJECT:id/version')
target_version = 'Version : 1.2.0.133'
has_correct_version = False

for elem in version_elements:
    # 遍历每个WebElement对象时再取文本
    elem_text = elem.text.strip()
    if elem_text == target_version:
        has_correct_version = True
        break

if has_correct_version:
    print('Step 46. NAS version is displayed correctly - PASS')
else:
    print('Step 46. NAS version is incorrect - Fail')
time.sleep(2)

EC等待时的报错修复

EC等待操作返回的是WebElement对象,不要在EC条件里直接调用.text,等拿到返回的元素对象后再提取文本即可:

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

# 显式等待10秒,直到元素可见,返回WebElement对象
wait = WebDriverWait(driver, 10)
version_elem = wait.until(EC.visibility_of_element_located((By.ID, 'com.project.PROJECT:id/version')))
# 拿到元素对象后再提取文本
version = version_elem.text.strip()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 13:15:03