WebDriverException:消息:类型错误:矩形未定义

Mat*_*dor 8 firefox selenium python-3.x selenium-webdriver geckodriver

我正在尝试使用 selenium 从带有 python 脚本的网站自动下载数据,但出现以下错误:

"WebDriverException: Message: TypeError: rect is undefined".
Run Code Online (Sandbox Code Playgroud)

代码试用:

from selenium import webdriver
from selenium.webdriver.common import action_chains

driver = webdriver.Firefox()
url="https://www.hlnug.de/?id=9231&view=messwerte&detail=download&station=609"
driver.get(url)
Run Code Online (Sandbox Code Playgroud)

现在我定义了要单击的复选框并尝试单击它:

temp=driver.find_element_by_xpath('//input[@value="TEMP"]')
action = action_chains.ActionChains(driver)

action.move_to_element(temp)
action.click()
action.perform()
Run Code Online (Sandbox Code Playgroud)

我已经在网上搜索了 2 个小时,但没有任何成功。因此,欢迎任何想法!

非常感谢!

Deb*_*anB 7

这个错误信息...

WebDriverException: Message: TypeError: rect is undefined
Run Code Online (Sandbox Code Playgroud)

...意味着当您尝试与之交互时,所需的WebElement可能没有定义客户端矩形

根据TypeError: rect is undefined, when using Selenium Actions and element is not displayed.主要问题,尽管您尝试与之交互的所需元素 [即调用click()]存在HTML DOM 中,不可见,未显示

原因

最可能的原因和解决方法如下:

  • 在您尝试单击元素时继续前进,此时所需的元素可能无法交互,因为某些JavaScript / Ajax调用可能仍处于活动状态。
  • 元素在视口之外

解决方案

  • 诱导WebDriverWait使元素可点击,如下所示:

    temp = wait.until(EC.element_to_be_clickable((By.XPATH, "//input[@value="TEMP"]")))
    action = action_chains.ActionChains(driver)
    action.move_to_element(temp)
    action.click()
    action.perform()
    
    Run Code Online (Sandbox Code Playgroud)
  • 使用execute_script()方法滚动元素查看如下:

    temp = driver.find_element_by_xpath("//input[@value="TEMP"]")
    driver.execute_script("arguments[0].scrollIntoView();", temp);
    action = action_chains.ActionChains(driver)
    action.move_to_element(temp)
    action.click()
    action.perform()
    
    Run Code Online (Sandbox Code Playgroud)


Jef*_*ffC 7

有两个元素与该定位符匹配。第一个不可见,所以我假设您要单击第二个。

temp = driver.find_elements_by_xpath('//input[@value="TEMP"]')[1] # get the second element in collection
action = action_chains.ActionChains(driver)

action.move_to_element(temp)
action.click()
action.perform()
Run Code Online (Sandbox Code Playgroud)

  • 当您编写自动化时,您应该始终检查浏览器中的定位器。我更喜欢 Chrome 开发工具。在 Chrome 中打开页面并按 F12。使用`$$()` 来测试CSS 选择器,使用`$x()` 来测试XPath。在这种情况下,您将运行 `$x('//input[@value="TEMP"]')` 并看到返回了两个元素。单击并悬停在第一个上以查看它在页面上不可见。单击并悬停在第二个上以查看它是否可见。现在,您甚至可以在开始编写代码之前避免这个问题。 (3认同)