在 Chrome 上使用 Python 的 Selenium webdriver - 滚动到元素的确切中间

Shi*_*zle 4 python selenium-chromedriver selenium-webdriver

我试图仅通过使用 XPATH 获取元素来单击它。我得到一个异常,该元素在给定位置不可点击。

我确定元素的中心是可点击的,那么我如何获得元素的确切中间(x,y)并使用 Python 使用 Selenium 点击它?

编辑:

我找到了这个问题的解决方案:

driver.execute_script("arguments[0].scrollIntoView(true);", element)
time.sleep(0.5)
element.click()
Run Code Online (Sandbox Code Playgroud)

time.sleep 是缺失的环节。

Sau*_*aur 6

实际上 selenium 本身会尝试单击元素中心位置的元素,因此当目标元素由于窗口大小或任何其他原因而被其他元素覆盖时,通常会发生此异常,例如它会隐藏在滚动条内等。

所以基本上,如果你想将确切的元素放入视口,所以你可以点击它,你应该尝试使用scrollIntoView()将当前元素滚动到浏览器窗口的可见区域的方法,如下所示:-

element = driver.find_element..
driver.execute_script("arguments[0].scrollIntoView()", element)
Run Code Online (Sandbox Code Playgroud)