【发布时间】:2020-11-01 21:10:18
【问题描述】:
我正在使用 Selenium 进行测试。我想点击一个元素。该元素非常可点击和可见,但恰好元素的中间点被遮挡,导致错误。
这是一个 MCVE:
HTML 代码(link to demo):
<style>
button {
width: 90vw;
height: 90vh;
position: fixed;
top: 5vh;
left: 5vw;
}
.cover {
background: grey;
opacity: 0.3;
width: 80vw;
height: 80vh;
position: fixed;
top: 10vh;
left: 10vw;
}
</style>
<button onclick="alert('hi');">
Click me!
</button>
<div class="cover">
I'm in the way!
</div>
Python 硒代码:
from selenium import webdriver
driver = webdriver.Chrome()
driver.implicitly_wait(10)
driver.get("https://blissfulpreciouslanservers--five-nine.repl.co/")
button = driver.find_element_by_tag_name("button")
button.click()
结果:
selenium.common.exceptions.ElementClickInterceptedException: Message: element click intercepted: Element <button onclick="alert('hi');">...</button> is not clickable at point (451, 450). Other element would receive the click: <div class="cover">...</div>
这似乎是 Selenium 的一个相当可悲的限制。该按钮是可点击的,但不是所有点。我不想摆弄滚动和坐标。
一般有很多关于异常的类似问题,例如:
- Can not click on a Element: ElementClickInterceptedException in Splinter / Selenium
- Selenium can't click element because other element obscures it
- Element not clickable since another element obscures it in python
但是,这些问题从来都不是专门针对仅部分模糊的元素,所以我没有设法找到我自己问题的正确答案。其他问题的答案通常分为以下几类:
- 等到元素可点击。不适用于此处。
- 使用动作链,例如
ActionChains(driver).move_to_element(button).click().perform()。这无济于事,因为.move_to_element()moves to the middle of the element。 - 使用 JavaScript 执行点击。看来我可能不得不求助于这个,但这很不令人满意。我仍然想验证该元素至少在某处是可点击的,而不是绕过所有检查。
【问题讨论】:
-
动作链也可以移动偏移量,因此您可以移动到某个 x,y 位置。
-
@arundeepchohan 手动执行此操作会使测试的编写和维护变得更加困难。我想避免它。
标签: python selenium selenium-webdriver selenium-webdriver-python