目的:
(1)滑動頁面的滾動條到頁面最下方
(2)滑動頁面的滾動條到頁面某個元素
(3)滑動頁面的滾動條向下移動某個數量的像素
測試的網址:
http://www.seleniumhq.org/
代碼如下:
from selenium import webdriver import unittest import traceback #導入堆棧類 import time class TestDemo(unittest.TestCase): def setUp(self): #啟動Chrome瀏覽器 self.driver = webdriver.Chrome() self.driver.implicitly_wait(30) def test_scroll(self): url = "http://www.seleniumhq.com/" #訪問selenium官網首頁 self.driver.get(url) try: #使用JavaScript的scrollTo函數和document.body.scrollHeight參數 #將頁面的滾動條滑動到頁面的最下方 self.driver.execute_script("window.scrollTo(100, document.body.scrollHeight);") #停頓5秒用於驗證滾動條是否滑動到指定位置 time.sleep(5) #使用JavaScript的scrollIntoView函數將被遮擋的元素滾動到可見屏幕上 #scrollIntoView(true)表示將元素滾動屏幕中間 #scrollIntoView(false)表示將元素滾動到屏幕底部 self.driver.execute_script("document.getElementById('choice').scrollIntoView(true);") #停頓5秒用於驗證滾動條是否滑動到指定位置 time.sleep(5) #使用JavaScript的scrollBy方法,使用0和400橫坐標參數 self.driver.execute_script("window.scrollBy(0,400);") #停頓5秒用於驗證滾動條是否滑動到指定位置 time.sleep(3) except Exception as e: #打印異常堆棧信息 print(traceback.print_exc()) def tearDown(self): #退出Chrome瀏覽器 self.driver.quit() if __name__ == '__main__': unittest.main()