【问题标题】:Selenium w/Python3 - AttributeError: 'str' object has no attribute 'tag_name'Selenium w/Python3 - AttributeError:'str'对象没有属性'tag_name'
【发布时间】:2018-10-19 11:58:32
【问题描述】:

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'

【问题讨论】:

  • 你能发布你的整个例子吗?
  • 哪一行出现错误?
  • 对不起,是的,我应该说错误来自 sel = Select('teamElement') 行。回溯(最后一次调用):文件“/Users/jamesstott/PycharmProjects/basics/RunChromeTests.py”,第 40 行,在 中 sel = Select('teamElement') 文件“/Users/jamesstott/PycharmProjects/venv/ lib/python3.6/site-packages/selenium/webdriver/support/select.py",第 36 行,在 init 如果 webelement.tag_name.lower() != "select": AttributeError: ' str' 对象没有属性 'tag_name'

标签: python selenium pycharm


【解决方案1】:

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")

【讨论】:

  • 哇,谢谢。那行得通。我不敢相信事情就这么简单。
【解决方案2】:

根据 API Docs,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)

【讨论】:

    猜你喜欢
    • 2014-05-26
    • 2021-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-26
    • 1970-01-01
    • 2018-09-10
    相关资源
    最近更新 更多