JavaScript控制瀏覽器滾動條
在訪問頁面上的展現結果超過一屏時,如果想瀏覽或操作屏幕下半部分的內容,由於被屏幕遮擋,因此無法操作對應的元素。此時,就需要借助滾動條來拖動屏幕,實現瀏覽更多的內容或使被操作的元素展現在屏幕上。注意,滾動條是無法直接被定位到的,WebDriver中也沒有直接的方法控制滾動條。此時便需要借助JavaScript來操作滾動條。
一、滾動條上下滾動
滾動條回到底部的JS語句,如下:
js_bottom = "var q=document.documentElement.scrollTop=10000" # 滾動條回到底部
滾動條回到頂部的JS語句,如下:
js_top = "var q=document.documentElement.scrollTop=0" # 滾動條回到頂部
示例代碼:
from time import sleep
from selenium import webdriver
class TestBaidu:
def setup(self):
self.url = "https://www.baidu.com/"
self.driver = webdriver.Chrome()
self.driver.set_window_size(800, 1000)
self.driver.get(self.url)
self.driver.implicitly_wait(5)
def teardown(self):
sleep(3)
self.driver.quit()
def test_locator_by_js_01(self):
"""
JS定位,瀏覽器滾動底部,然后再滾動到頂部
"""
js_bottom = "var q=document.documentElement.scrollTop=10000" # 滾動條回到底部
js_top = "var q=document.documentElement.scrollTop=0" # 滾動條回到頂部
self.driver.find_element_by_id("kw").send_keys("linux")
self.driver.find_element_by_id("su").click()
sleep(2)
self.driver.execute_script(js_bottom)
sleep(2)
self.driver.execute_script(js_top)
sleep(2)
二、滾動條左右滾動
橫向滾動條左右滑動,語句如下:
js = "window.scrollTo(800,1000)" # 800、1000對應的是x軸和y軸
示例代碼:
from time import sleep
from selenium import webdriver
class TestBaidu:
def setup(self):
self.url = "https://www.baidu.com/"
self.driver = webdriver.Chrome()
self.driver.set_window_size(800, 1000)
self.driver.get(self.url)
self.driver.implicitly_wait(5)
def teardown(self):
sleep(3)
self.driver.quit()
def test_locator_by_js_02(self):
"""
JS定位,橫向滾動條左右滑動
"""
js = "window.scrollTo(800,1000)" # 800、1000對應的是x軸和y軸
sleep(2)
self.driver.execute_script(js)
sleep(2)
三、scrollTo方法控制滾動條
滾動條回到底部的JS語句,如下:
js_bottom = "window.scrollTo(0,document.body.scrollHeight)" # 滾動條回到底部
滾動條回到頂部的JS語句,如下:
js_top = "window.scrollTo(0,0)" # 滾動條回到頂部
其他說明:
document.body.scrollWidth:網頁正文全文寬度,包括(存在滾動條)未見區域;
document.body.scrollHeight:網頁正文全文高度,包括(存在滾動條)未見區域;
document.documentElement.clientWidth:可見區域寬度,不包含存在滾動條時的未見區域;
document.documentElement.clientHeight:可見區域高度,不包含存在滾動條時的未見區域;
document.documentElement.scrollTop=200:設置或返回匹配元素相對滾動條頂部的偏移;
document.documentElement.scrollLeft=200:設置或返回匹配元素相對滾動條左側的偏移;
window.scrollTo(200,300):設置滾動條的left(橫坐標)=200,top(縱坐標)=300。
示例代碼:
from time import sleep
from selenium import webdriver
class TestBaidu:
def setup(self):
self.url = "https://www.baidu.com/"
self.driver = webdriver.Chrome()
self.driver.set_window_size(800, 1000)
self.driver.get(self.url)
self.driver.implicitly_wait(5)
def teardown(self):
sleep(3)
self.driver.quit()
def test_scroll_to_by_js(self):
js_bottom = "window.scrollTo(0,document.body.scrollHeight)" # 滾動條回到底部
js_top = "window.scrollTo(0,0)" # 滾動條回到頂部
self.driver.find_element_by_id("kw").send_keys("linux")
self.driver.find_element_by_id("su").click()
sleep(2)
self.driver.execute_script(js_bottom)
sleep(2)
self.driver.execute_script(js_top)