ElementNotInteractableException:消息:尝试使用Selenium和Python单击元素时,元素无法滚动到视图中

时间:2019-03-18 19:21:24

标签: python selenium selenium-webdriver webdriver webdriverwait

我有此代码:

driver.switch_to.window(window_after)

try:
    myElem = WebDriverWait(driver, delay).until(EC.presence_of_element_located((By.NAME, '_eventId_confirmed')))
    print ("Page 2 is ready!")
except TimeoutException:
    print ("Loading took too much time!")

btn = driver.find_element_by_name('_eventId_confirmed')

btn.click()

如您所见,我首先切换窗口,然后检查一个元素,获取该元素(一个按钮),最后尝试单击该按钮。这种方法可能在3次中有2次有效,但经常会因此错误消息而失败

selenium.common.exceptions.ElementNotInteractableException: Message: Element <button class="btn" name="_eventId_confirmed"> could not be scrolled into view

从视觉上看执行时的流程似乎一切正常(我的第一个猜测是窗口开关未按预期工作),浏览器最终处于预期状态,在此状态下,我可以手动单击此按钮。有趣的是,此错误发生时没有超时或类似情况,它在执行过程中立即发生。

有什么想法吗?

3 个答案:

答案 0 :(得分:1)

当您要单击的元素出现在页面上但不完全可见并且硒试图单击的点不可见时,通常会出现此问题。
在这种情况下,您可以使用javascript单击元素,该元素实际上直接在页面的html结构上运行。
您可以像这样使用它:

element = driver.find_element_by_name("_eventId_confirmed")
driver.execute_script("arguments[0].click();", element)

答案 1 :(得分:0)

这是2个选项。

使用硒location_once_scrolled_into_view方法:

btn.location_once_scrolled_into_view

使用Javascript:

driver.execute_script("arguments[0].scrollIntoView();",btn)

示例代码:

url = "https://stackoverflow.com/questions/55228646/python-selenium-cant-sometimes-scroll-element-into-view/55228932?    noredirect=1#comment97192621_55228932"
driver.get(url)
element = driver.find_element_by_xpath("//a[.='Contact Us']")
element.location_once_scrolled_into_view
time.sleep(1)
driver.find_element_by_xpath("//p[.='active']").location_once_scrolled_into_view
driver.execute_script("arguments[0].scrollIntoView();",element)

答案 2 :(得分:0)

最后一步是在所需元素上调用click(),因此,除了使用expected_conditions作为presence_of_element_located()之外,还需要如下使用element_to_be_clickable()

try:
    myElem = WebDriverWait(driver, delay).until(EC.element_to_be_clickable((By.NAME, '_eventId_confirmed')))