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
相关产品推荐
相关产品推荐

