Last active
June 26, 2022 13:17
-
-
Save iamumairayub/87e231c0e4c4555af56f72cd469b1efb to your computer and use it in GitHub Desktop.
Slowly scroll to an element and make it visible in view-port in Python Selenium
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def slow_scroll_to_element(self, driver, element_selector=None, target_yth_location=None): | |
current_scroll_position = int(driver.execute_script("return window.scrollY")) | |
if element_selector: | |
target_yth_location = int(driver.execute_script("return document.querySelector('{}').getBoundingClientRect()['top'] + window.scrollY".format(element_selector))) | |
scrollSpeed = 100 if target_yth_location-current_scroll_position > 0 else -100 | |
def chunks(a, n): | |
k, m = divmod(len(a), n) | |
return (a[i*k+min(i, m):(i+1)*k+min(i+1, m)] for i in range(n)) | |
for l in list(chunks(list(range(current_scroll_position, target_yth_location, scrollSpeed)) + list([target_yth_location+(-scrollSpeed if scrollSpeed > 0 else scrollSpeed)]), 3)): | |
for pos in l: | |
driver.execute_script("window.scrollTo(0, "+str(pos)+");") | |
time.sleep(0.1) | |
time.sleep(random.randint(1,3)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment