WebDriver高級應用——操作Web頁面的滾動條


目的:

(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()

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM