AttributeError:“WebElement”对象在通过Django使用Selenium Python将函数Select移动到公共文件时没有属性“copy”错误

2024-06-09 08:32:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这样一个HTML元素

<select id="my_id">
<option value="">ALL</option>
<option value="1.0">ALL</option>
<option value="2.0">A</option>
<option value="3.0">B</option>
<option value="4.0">C</option>
</select>

当我在测试文件中使用define函数时,我想选择它的一个值 它会正常工作的

my_test_file.py
def _find_and_select(self, elm_id, value):
    select_item = Select(self.browser.find_element_by_id(elm_id))
    select_item.select_by_value(value)
self._find_and_select("my_id", "1.0")

但是当我移动到一个公共测试文件时

common_file.py
class Common:
    @staticmethod
    def _find_and_select(browser, elm_id, value):
        select_item = Select(browser.find_element_by_id(elm_id))
        select_item.select_by_value(value)

my_test_file.py
Common._find_and_select(self.browser, "my_id", "1.0")

这将导致错误:

Traceback (most recent call last):
  File "D:\iBNet-Prj\ibnet\apps\autotest\contract\tests.py", line 251, in test_search
    CommonTest._find_and_select(self.browser, "contractLoanStatus", loanStatus[0])
  File "D:\iBNet-Prj\ibnet\apps\common_test.py", line 467, in _find_and_select
    select_item = Select(browser.find_element_by_id(elm_id))
  File "D:\iBNet-Prj\venv\lib\site-packages\django\forms\widgets.py", line 558, in __init__
    super().__init__(attrs)
  File "D:\iBNet-Prj\venv\lib\site-packages\django\forms\widgets.py", line 201, in __init__
    self.attrs = {} if attrs is None else attrs.copy()
AttributeError: 'WebElement' object has no attribute 'copy'

Tags: andpytestselfbrowseridbyvalue
1条回答
网友
1楼 · 发布于 2024-06-09 08:32:03

此错误消息

  File "D:\iBNet-Prj\ibnet\apps\common_test.py", line 467, in _find_and_select
    select_item = Select(browser.find_element_by_id(elm_id))
  File "D:\iBNet-Prj\venv\lib\site-packages\django\forms\widgets.py", line 558, in __init__
    super().__init__(attrs)
  File "D:\iBNet-Prj\venv\lib\site-packages\django\forms\widgets.py", line 201, in __init__
    self.attrs = {} if attrs is None else attrs.copy()
AttributeError: 'WebElement' object has no attribute 'copy'

…表示代码行select_item = Select(browser.find_element_by_id(elm_id))失败,在您使用框架时super().__init__(attrs)被调用,从而产生错误:

AttributeError: 'WebElement' object has no attribute 'copy'

解决方案

理想情况下,要选择所需元素,您必须为element_to_be_clickable()引入WebDriverWait,并且您可以使用以下Locator Strategies之一:

  • 使用CSS_SELECTOR

    select_item = Select(WebDriverWait(browser, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "select#my_id"))))
    select_item.select_by_value(value)
    
  • 使用XPATH

    select_item = Select(WebDriverWait(browser, 10).until(EC.element_to_be_clickable((By.XPATH, "//select[@id='my_id']"))))
    select_item.select_by_value(value)
    
  • 注意:您必须添加以下导入:

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

相关问题 更多 >