Selenium 如何点击 50% 在屏幕上和 50% 不在屏幕上的元素?

How does Selenium click on elements that are 50% on screen and 50% not on screen?

有一个 div-元素。其大小的 50% 在屏幕上。其他 50% 超过屏幕高度并且不可见。 无法滚动。

我尝试使用 Selenium 自动执行测试并单击该 div 元素,但有时有效,有时无效。

为什么 Selenium 不直接点击 div 的 "on-screen-area"?

这个功能是如何实现的?当我告诉 Selenium 单击一个巨大的 div 元素时,它会单击那个 div 上的随机位置吗?

如果您是基于 xpath、id 等定位器进行点击,是的,它会点击随机位置。但只要单击元素并执行该单击的结果操作就没有关系。

关于有时它是否有效,如果您检查了要启用或单击的按钮,它将始终有效。

元素的视图中心点

根据 WebDriver W3C 规范 元素的 in-view center point is the origin position of the rectangle that is the intersection between the element’s first DOM client rectangle and the initial viewport

给定一个已知在视图中的元素,可以这样计算:

  1. 令矩形成为通过对元素调用 getClientRects 返回的 DOMRect 序列的第一个元素。
  2. 左边为max(0, min(x坐标, x坐标+宽度尺寸)).
  3. 设右边为min(innerWidth, max(x坐标, x坐标+宽度尺寸)).
  4. 设top为max(0, min(y坐标, y坐标+高度尺寸)).
  5. 设bottom为min(innerHeight, max(y coordinate, y coordinate + height dimension)).
  6. 设 x 为 floor((left + right) ÷ 2.0).
  7. 设y为floor((top + bottom) ÷ 2.0).
  8. Return (x, y) 对。

如果一个元素是它自己的指针交互绘制树的成员,那么它就在视图中,假装它的指针事件没有被禁用。


元素点击

根据文档,Element Click 命令滚动到元素的视图中(如果它还不是指针可交互的),并单击其在视图中的中心点。

注意:如果元素中心点被其他元素遮挡,则返回元素点击拦截错误。如果元素在视口之外,则返回元素不可交互错误。


解决方案

在这种情况下,有两种可能的解决方案如下:

  1. 可以诱导WebDriverWait setting the expected_conditions as element_to_be_clickable()。所以实际上你的代码行将是:

    WebDriverWait(browser, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, ".reply-button"))).click()
    
  2. 可以分别使用move_to_element(to_element) and click(on_element=None)方法。所以实际上你的代码行将是:

    ActionChains(driver).move_to_element(element).click(element).perform()
    

参考

您可以在

中找到相关讨论