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)