python+js控制頁面的滾動條滑動


from seleniumimport webdriver

from selenium.common.exceptionsimport WebDriverException

import unittest

import traceback

import time

class TestDemo(unittest.TestCase):

? ? def setUp(self):

? ? ? ? #啟動瀏覽器

? ? ? ? self.driver= webdriver.Chrome(executable_path="C:\Python\Python37\chromedriver.exe")

def test_scroll(self):

? ? ? ? url= "https://www.baidu.com/s?word=2019-03-10%0D%0A%20%E5%8F%91&tn=41052153_3_dg"

? ? ? ? #訪問selenium官網(wǎng)首頁

? ? ? ? try:

? ? ? ? ? ? self.driver.get(url)

#使用js的scrollTo函數(shù)和document.body.scrollHeight參數(shù)

? ? ? ? ? ? #將頁面滾動條滑動到頁面的最下方

? ? ? ? ? ? self.driver.execute_script("window.scrollTo(100, document.body.scrollHeight);")

#停頓3秒 用于人工驗證滾動條是否滑動到指定的位置

? ? ? ? ? ? #根據(jù)測試需要 可注釋下面的停頓代碼

? ? ? ? ? ? time.sleep(3)

#使用js的scrollIntoView函數(shù)將被遮擋的元素滾動到可見屏幕上

? ? ? ? ? ? #停頓3秒 用于人工驗滾動條是否滑動到指定的位置

? ? ? ? ? ? #根據(jù)測試需要,可注釋下面的停頓代碼

? ? ? ? ? ? # time.sleep(3)

? ? ? ? ? ? #使用js的scrollBy方法,使用0和400橫縱坐標(biāo)參數(shù)

? ? ? ? ? ? #將頁面縱向滾動400像素

? ? ? ? ? ? self.driver.execute_script("window.scrollBy(0,-400);")

#根據(jù)測試需要 可注釋下面的停頓代碼

? ? ? ? ? ? time.sleep(3)

except Exception as e:

? ? ? ? ? ? #打印異常堆棧信息

? ? ? ? ? ? print(traceback.print_exc())

def tearDown(self):

? ? ? ? ? ? #退出Chrome瀏覽器

? ? ? ? ? ? self.driver.quit()

if __name__== '__main__':

? ? unittest.main()

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容