import unittest
from selenium import webdriver
import time
import traceback
class MyTestCase(unittest.TestCase):
def setUp(self):
#启动火狐浏览器
self.driver=webdriver.Chrome(executable_path=’/python/driver/chromedriver’)
def test_scorll(self):
url=“https://www.getpostman.com/”
try:
self.driver.get(url)
#使用Javascript的scroll函数和document.body.scrollHeight参数
#将页面的滚动条滑动到页面的最下方
size=self.driver.get_window_size()
print(“宽是:”,size[‘width’])
print(“高是:”, size[‘height’])
self.driver.execute_script
(“window.scrollTo(200,document.body.scrollHeight);”)
#停顿3秒
time.sleep(3)
print(“这时滚动到最下方”)
#使用JavaScript的scrollIntoView函数将被遮挡的元素滚动到可见屏幕上
#scrollIntoView(true)表示将元素滚到屏幕中间
# scrollIntoView(false)表示将元素滚到屏幕底部
self.driver.execute_script
(“document.getElementById(‘sidebar-toggleable’).scrollIntoView(true);”)
time.sleep(3)
print(“这时滚动到中间”)

该篇博客介绍如何利用Python的selenium库操作网页滚动条。首先启动Chrome浏览器,访问指定URL,然后通过execute_script执行JavaScript代码实现滚动条滑动到页面底部和将特定元素滚动到屏幕中间。此外,还展示了使用scrollBy方法按像素滚动页面。

1万+

被折叠的 条评论
为什么被折叠?



