I need to be able to scroll up and after that down to find some element with Selenium.
I already saw many questions and answers, the main idea I found is self.web_driver.execute_script("return arguments[0].scrollIntoView(true);", element)
and this is what I currently have in my code. But this is not good enough since this code is scrolling down only so this fails to find the element in case it is located in the upper part of the rollable view.
So I need a script that first scrolls up (page Up?) and after that begins scrolling down.
I tried something like this
self.web_driver.execute_script("return arguments[0].scrollIntoView(true);", element)
self.web_driver.execute_script("window.scrollTo(0, -document.body.scrollHeight);")
self.web_driver.execute_script("return arguments[0].scrollIntoView(true);", element)
but this doesn't scroll up :(
To scroll down to the bottom of a webpage using Selenium, you can use the execute_script() function to execute the JavaScript function window. scrollTo() and pass 'document. body. scrollHeight' for the second parameter.
The JavaScriptExecutor provides an interface that enables QAs to run JavaScript methods from Selenium scripts. Hence, to scroll up or down with Selenium, a JavaScriptExecutor is a must. The scrollBy() method involves two parameters, x, and y, that represent the horizontal and vertical pixel values, respectively.
You can try below code to scroll page up:
from selenium.webdriver.common.keys import Keys
self.web_driver.find_element_by_tag_name('body').send_keys(Keys.HOME)
Another way (preferred) you can scroll up to required element:
element = self.web_driver.find_element_by_xpath('SOME_XPATH') # you can use ANY way to locate element
coordinates = element.location_once_scrolled_into_view # returns dict of X, Y coordinates
self.web_driver.execute_script('window.scrollTo({}, {});'.format(coordinates['x'], coordinates['y']))
I have discovered a handy tricky hacky stuff
over the years (I've been using Selenium for 150 years).
Whenever you're unable to scroll up a form, just send keys into an input on the top of the page. The driver will find it and will automagically scroll up the page to perform the action.
Whenever I think about this trick, I realize being an old man isn't that bad.
Good luck you fresh sailor, see you on the shores of Selenia.
Try this, it works good:
view_port_height = "var viewPortHeight = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);"
element_top = "var elementTop = arguments[0].getBoundingClientRect().top;"
js_function = "window.scrollBy(0, elementTop-(viewPortHeight/2));"
scroll_into_middle = view_port_height + element_top + js_function
driver.execute_script(scroll_into_middle, element)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With