Scroll page
In automated operations, if the web page Too long, and the element we need is not in the current visible page, then selenium cannot operate it; at this time, we need to scroll the page as we usually operate the browser to make the object we need to operate visible!
How to scroll the page:
-
window.scrollBy()
-
window.scrollBy(0,500 ) Scroll down 500 pixels
-
window.scrollBy(0,-500) scroll up 500 pixels
< li>
window.scrollBy(500,0)< /strong> Scroll 500 pixels to the right
-
-
window.scrollBy(-500,0) scroll left 500 pixels
li>
How to use: p>
-
Enter the above content in the developer tool–Console to achieve page scrolling
< /li>
-
Example: window .scrollBy(0,500) Scroll down 500 pixels
Selenium implements scrolling pages
-
driver.execute_script('window.scrollBy()')
-
< span style="font-size: 16px;">driver.execute_script("arguments[0].scrollIntoView();", < span style="color: #0000ff;">ele) scroll to the element elevisible
Code example:
from selenium import webdriver
import time
driver = webdriver.Chrome()
driver.implicitly_wait(10)
# Set window size
driver.set_window_size(800, 700)
driver.get('http://baidu.com span>')
# Baidu input box input selelnium python Enter
driver.find_element_by_id("kw").send_keys("selenium python ")
time.sleep(2)
# scroll down 200 pixels
driver.execute_script('window.scrollBy(0,200)')
time.sleep(2)
# scroll to the visible position of element ele
eles = driver.find_elements_by_css_selector('#rs table tr th a< span style="color: #800000;">')
ele = eles[0]
driver.execute_script("arguments[0].scrollIntoView(); ",ele)
time.sleep(2)
# scroll 200 pixels to the right
driver.execute_script('window.scrollBy(200,0)< span style="color: #800000;">')
time.sleep(2)
driver.quit()
from selenium < span style="color: #0000ff;">import webdriver
import time
driver = webdriver.Chrome()
driver.implicitly_wait(10)
# Set window size
driver.set_window_size(800, 700)
driver.get('http://baidu.com span>')
# Baidu input box input selelnium python Enter
driver.find_element_by_id("kw").send_keys("selenium python ")
time.sleep(2)
# scroll down 200 pixels
driver.execute_script('window.scrollBy(0,200)')
time.sleep(2)
# scroll to the visible position of element ele
eles = driver.find_elements_by_css_selector('#rs table tr th a< span style="color: #800000;">')
ele = eles[0]
driver.execute_script("arguments[0].scrollIntoView(); ",ele)
time.sleep(2)
# scroll 200 pixels to the right
driver.execute_script('window.scrollBy(200,0)< span style="color: #800000;">')
time.sleep(2)
driver.quit()