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

Selenium+Python3报错:'str' object has no attribute 'tag_name' 求助

解决Selenium Select下拉框的AttributeError问题

嘿,这个问题其实很容易搞定!你遇到的AttributeError: 'str' object has no attribute 'tag_name'错误,根源是你给Select类传了一个字符串,而不是实际的WebElement对象。

错误原因分析

Select构造函数要求传入的是通过find_element_*方法获取到的WebElement实例,但你写的是:

sel = Select('teamElement')

这里的'teamElement'是字符串,不是你之前获取的那个teamElement元素对象。Selenium会尝试去访问这个字符串的tag_name属性,字符串当然没有这个属性,所以报错了。

修正后的代码

把引号去掉,直接传入你已经获取到的WebElement对象就行:

from selenium import webdriver
from selenium.webdriver.support.select import Select

# 获取下拉框元素对象
teamElement = browser.find_element_by_id('id_team')
sel = Select(teamElement)  # 去掉引号!
sel.select_by_value("12")

额外优化建议

尽量别用time.sleep()这种固定等待,推荐用显式等待来确保元素加载完成,这样代码更稳定:

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

# 等待下拉框元素可被定位,最多等10秒
teamElement = WebDriverWait(browser, 10).until(
    EC.presence_of_element_located((By.ID, 'id_team'))
)
sel = Select(teamElement)
sel.select_by_value("12")

这样就能顺利操作下拉框啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 06:34:35