1+ # scrolling is also mouse operation but we can't perform it using actionchains
2+ # it is because when content of the web page can't be showed on one page then scroll bar is added by the browser
3+ # so scroll bar is not from the application it is from the browser hence can't be handled by actionchains
4+ # as scoll bar is designed using javascript so we have to write some script to handle it
5+ # there are four ways in which we can perform scrolling
6+ # Note : uncomment the option you want to test
7+
8+ import time
9+ from selenium import webdriver
10+ from selenium .webdriver import ActionChains
11+ from selenium .webdriver .chrome .service import Service
12+ from selenium .webdriver .common .by import By
13+
14+ options = webdriver .ChromeOptions ()
15+ options .add_experimental_option ("detach" , True )
16+
17+ ser_obj = Service ("C:\Drivers\chromedriver\chromedriver.exe" )
18+ driver = webdriver .Chrome (options = options , service = ser_obj )
19+
20+ driver .implicitly_wait (3 )
21+ driver .get ("https://www.countries-ofthe-world.com/flags-of-the-world.html" )
22+
23+ # 1 : scoll down page by pixels
24+
25+ # driver.execute_script("window.scrollBy(0,3000)") # inside the execute we passed javascript statement and passed a window methode
26+ # # we use execute_script for executing javascript statements
27+
28+ # value = driver.execute_script("return window.pageYOffset;") # semicolon will also be added since it is JS
29+ # print("number of pixel scrollbar moved: ", value) # 2999
30+
31+ # 2 : scoll down page till the element is visible/found
32+ # for that we have to first capture that element
33+
34+ # flag = driver.find_element(By.XPATH, "//img[@alt='Flag of Pakistan']")
35+ # driver.execute_script("arguments[0].scrollIntoView()",flag) # passed two arguments
36+
37+
38+ # now if you want to know how much the scroll bar is moved use this statement
39+ # value = driver.execute_script("return window.pageYOffset;")
40+ # print("number of pixel scrollbar moved: ", value)
41+
42+ # 3 : scroll down till the end page
43+ driver .execute_script ("window.scrollBy(0, document.body.scrollHeight)" , "" )
44+
45+ # now if you want to know how much the scroll bar is moved use this statement
46+ value = driver .execute_script ("return window.pageYOffset;" )
47+ print ("number of pixel scrollbar moved: " , value ) # 9560.7548828125
48+
49+ time .sleep (4 )
50+
51+ # 4 : scroll up the page to the start
52+ driver .execute_script ("window.scrollBy(0, -document.body.scrollHeight)" , "" ) # here we have added the substract sign
53+
54+ time .sleep (3 )
55+ driver .close ()
0 commit comments