纵向滚动条上下滑动
代码:
execute_script("window.scrollTo(document.body.scrollHeight, height)")
# height: 距页面顶部的位置高度
- 滚动条滑动到顶部,设
height = 0即可:execute_script("window.scrollTo(document.body.scrollHeight, 0)")
PS:如果想要滑动到页面底部,一种方式可以设置
height值足够大,超过页面整体高度;
-
不过我们基本采用另外一种方式,设置
height = 0,与document.body.scrollHeight前后位置调换execute_script("window.scrollTo(0, document.body.scrollHeight)") -
其他位置
- 移动到使元素顶部与窗口的顶部对齐位置
execute_script("arguments[0].scrollIntoView();",element) -
移动到使元素底部与窗口的底部对齐位置
execute_script("arguments[0].scrollIntoView(false);",element)- element.scrollIntoView()
- 参数默认为true,使element的顶部与视图(容器)顶部对齐;参数为false:使element的底部与视图(容器)底部对齐
- element.scrollIntoView()
-
实例:
from selenium import webdriver
from time import sleep
br = webdriver.Chrome()
# 设置浏览器高度和宽度(set_window_size(宽, 高))
br.set_window_size(1800, 980)
# 访问一个页
br.get("https://www.baidu.com")
# 新标签打开超链接,切换到第二个标签
sleep(1)
tab2 = br.find_elements_by_class_name("mnav.c-font-normal.c-color-t")
tab2[0].click()
windows_handles = br.window_handles
br.switch_to.window(windows_handles[1])
print("当前页面URL:{}".format(br.current_url))
# 滚动条操作
sleep(2)
br.execute_script("window.scrollTo(0, document.body.scrollHeight)") # 滑动到底部
sleep(2)
br.execute_script("window.scrollTo(document.body.scrollHeight, 0)") # 滑动到顶部
sleep(2)
br.execute_script("window.scrollTo(document.body.scrollHeight, 50)") # 滑动到距离顶部50像素
# 结束进程
br.quit()
本文介绍使用Selenium库中的execute_script方法实现网页滚动条的自动化控制。包括将滚动条滑动到页面顶部、底部及指定位置的方法,并演示了如何使特定元素与窗口顶部或底部对齐。

4006

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



