首页 文章

Selenium w / Python3 - AttributeError:'str' object没有属性'tag_name'

提问于
浏览
1

使用Selenium / Python自动新手 . 我正在阻止自动化注册表单 . 下拉是必需的元素,但我收到以下错误...

AttributeError:'str'对象没有属性'tag_name'

我在下面发布了我的代码,在网上找不到任何答案,为什么会这样 . 任何/所有帮助非常感谢 .

from selenium import webdriver
from selenium.webdriver.support.select import Select
teamElement = browser.find_element_by_id('id_team')
time.sleep(2)
sel = Select('teamElement')
sel.select_by_value("12")

错误来自sel = Select('teamElement')行 .

Traceback (most recent call last):
 File "/Users/jamesstott/PycharmProjects/basics/RunChromeTests.py", 
 line 40, in <module>
 sel = Select('teamElement')
 File "/Users/jamesstott/PycharmProjects/venv/lib/python3.6/site-packages/selenium/webdriver/support/select.py", line 36, in __init__
 if webelement.tag_name.lower() != "select":
 AttributeError: 'str' object has no attribute 'tag_name'

2 回答

  • 2

    Select选择WebElement类型参数而不是字符串类型 . 改变以下行

    sel = Select('teamElement')
    

    sel = Select(teamElement)

    完整代码,

    from selenium import webdriver
    from selenium.webdriver.support.select import Select
    teamElement = browser.find_element_by_id('id_team')
    time.sleep(2)
    sel = Select(teamElement)
    sel.select_by_value("12")
    
  • 0

    根据API文档,Select()接受 webelement 作为参数,定义如下:

    class selenium.webdriver.support.select.Select(webelement)
    
    A check is made that the given element is, indeed, a SELECT tag. If it is not, then an UnexpectedTagNameException is thrown.
    
    Args :  
    webelement - element SELECT element to wrap
    

    但是根据你的代码,你已经在单引号内传递了参数 teamElement (最初是一个WebElement),即 string . 因此,您会看到错误 .

    解决方案

    将参数 teamElement 作为WebElement传递给:

    sel = Select(teamElement)
    

相关问题