I have this code:
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()
as you can see I first switch window and then check for an element, get that element (a button) and finally try to click on said button. This works maybe 2 out of 3 times but ever so often does it fail with this error message
selenium.common.exceptions.ElementNotInteractableException: Message: Element <button class="btn" name="_eventId_confirmed"> could not be scrolled into view
When visually looking at the flow when it is executing everything seems fine (my first guess was that the window switch didn't work as expected) and the browser ends up in the expected state where I am able to manually click this button. Interestingly enough, there is no timeout or similar when this error occurs, it happens instantly during execution.
Any ideas what's going on here?
This problem usually arises when the element you are trying to click is present on the page but it is not fully visible and the point where selenium tries to click is not visible.
In this case, you can use javascript to click on the element, which actually operates directly on the html structure of the page.
You can use it like:
element = driver.find_element_by_name("_eventId_confirmed")
driver.execute_script("arguments[0].click();", element)
Here are the 2 options.
Using selenium location_once_scrolled_into_view
method:
btn.location_once_scrolled_into_view
Using Javascript:
driver.execute_script("arguments[0].scrollIntoView();",btn)
Sample Code:
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)
As your final step is to invoke click()
on the desired element, so instead of using the expected_conditions as presence_of_element_located()
you need to use element_to_be_clickable()
as follows:
try:
myElem = WebDriverWait(driver, delay).until(EC.element_to_be_clickable((By.NAME, '_eventId_confirmed')))