硒元素点击位置不对



我们正在等待一个由xpath标识的按钮可以点击:

ExpectedConditions.elementToBeClickable()

然后点击Selenium中的这个按钮。

然后我们得到一个错误:

another element would receive the click at position (x, y).

在页面加载过程中,此按钮可能会在页面上稍微移动,因为它旁边的其他按钮正在加载。

为什么Selenium会报告按钮是可点击的,然后却无法点击?我知道这就是这种情况的原因。此执行发生在同一行中。

我们该如何解决这个问题?

假设您想要与一个按钮交互,而该按钮位于页面中间。

案例1:

您不能通过自动化脚本以全屏模式打开浏览器。那么它的位置将不会在页面的中间。

你可以通过引入来解决这个问题

driver.maximize_window()

情况2:

也许在自动化脚本中,会出现一些pop upads,这实际上会将按钮隐藏在后台。在这种情况下,您可能会遇到another element would receive the click at position (x, y).

解决方案:您应该确定它们是什么类型的pop up/Alert/ads,并分别处理它们,然后只有您才能与预期的按钮进行交互。

案例3:

也可能发生这种情况,因为您可能打开了日历(比如说日历来选择开始/结束日期(,然后因为硒无法访问日历视图下的web元素,只有日历视图才能获得点击。[这应该能回答你的问题]

通常,我在selenium脚本中使用actions classJSinject js code

如果您在Python中使用Selenium,那么您可以使用

  1. 使用ActionChains:

    ActionChains(driver).move_to_element(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "CSS here")))).click().perform()
    
  2. 使用execute_script:

    wait = WebDriverWait(driver, 20)
    button= wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "CSS here")))
    driver.execute_script("arguments[0].click();", button)
    

在Python中,您还需要以下导入:

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

使用ExpectedConditions.elementToBeClickable()允许我们的代码停止程序执行或冻结线程,直到我们传递的条件解决为止。以一定的频率调用条件,直到等待超时为止。这意味着,只要条件返回一个错误的值,它就会继续尝试和等待。因此,Explicit waits允许我们等待一个条件发生,该条件在浏览器及其DOM树和WebDriver脚本之间同步状态。

即使使用ExpectedConditions.elementToBeClickable(),在调用所需元素上的click((时也可能出现以下错误之一:

Element <a href="/path1/path2/menu">...</a> is not clickable at point (415, 697). Other element would receive the click: <div class="cc-content">...</div>

WebDriverException: Element is not clickable at point (36, 72). Other element would receive the click

原因及解决方案

发生这种错误的原因有很多,其中几个原因及其补救措施如下:

  • 虽然元素在Viewport中,但可能隐藏在cookie横幅后面。在这种情况下,在与所需元素交互之前,您必须接受cookie同意,如下所示:

    new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("cookieConsentXpath"))).click();
    new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("elementXpath"))).click();
    
  • 元素可以可点击,但位于加载程序后面。在这种情况下,在与所需元素交互之前,您必须等待加载程序消失,如下所示:

    new WebDriverWait(driver, 20).until(ExpectedConditions.invisibilityOfElementLocated(By.cssSelector("loader_cssSelector")));
    new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("element_cssSelector"))).click();
    

最新更新