selenium:操作滚动条的方法(8)

selenium支持几种操作滚动条的方法,主要介绍如下:

使用ActionChains 类模拟鼠标滚轮操作

使用函数ActionChains.send_keys发送按键Keys.PAGE_DOWN往下滑动页面,发送按键Keys.PAGE_UP往上滑动页面。

复制代码
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
driver = webdriver.Safari()
# 打开一个网页
driver.get("https://www.toutiao.com/")
driver.maximize_window()
sleep(6)
actions = webdriver.ActionChains(driver)
# 向下翻页
actions.send_keys(Keys.PAGE_DOWN).perform()
# 向上翻页
actions.send_keys(Keys.PAGE_UP).perform()

使用函数execute_script执行js脚本滚动页面

可以使用如下三种方式

1)使用window.scrollBy(x, y)

driver.execute_script('window.scrollBy(0, 1000)')

参数解释:

x:正数表示向右滑动的像素值,负数表示向左滑动的像素值

y:正数表示向下滑动的像素值,负数表示向上滑动的像素值

2)使用window.scrollTo(x, y)

driver.execute_script('window.scrollTo(0, 1000)')

参数解释:

x:正数表示向右滑动到某个像素值,负数表示向左滑动到某个像素值

y:正数表示向下滑动到某个像素值,负数表示向上滑动到某个像素值

3)使用document.documentElement.scrollTop设置滚动条高度

设置滚动高度为某个像素值:

driver.execute_script("document.documentElement.scrollTop=1000")

测试代码:使用上面3个️方式向下滚动,然后再向上滚动(中间通过sleep等待几秒方便观察效果).

复制代码
from selenium import webdriver
from selenium.webdriver.common.by import By
driver = webdriver.Safari()
# 打开一个网页
#driver.get("http://www.sahitest.com/demo/framesTest.htm")
driver.get("https://www.toutiao.com/")
driver.maximize_window()
sleep(6)
#向下滚动
driver.execute_script('window.scrollBy(0, 100)')
sleep(1)
driver.execute_script('window.scrollTo(0, 200)')
sleep(1)
driver.execute_script("document.documentElement.scrollTop=300")
sleep(1)
#向上滚动
driver.execute_script('window.scrollBy(0, -100)')
sleep(1)
driver.execute_script('window.scrollTo(0, -200)')
sleep(1)
driver.execute_script("document.documentElement.scrollTop=-300")
sleep(1)

使用函数execute_script执行js脚本滚动到特定元素

我们可以直接找到需要滚动到的元素位置,并使用scrollIntoView方法滚到该位置。

示例代码:

复制代码
from selenium import webdriver
from selenium.webdriver.common.by import By
driver = webdriver.Safari()
driver.get("https://www.toutiao.com/")
driver.maximize_window()
sleep(6)
# 找到某个目标元素
element = driver.find_element(By.XPATH,'//*[@id="root"]/div/div[5]/div[2]/div[6]/a[15]')
# 滚动到目标元素
driver.execute_script("arguments[0].scrollIntoView();", element)

共勉: 东汉·班固《汉书·枚乘传》:"泰山之管穿石,单极之绠断干。水非石之钻,索非木之锯,渐靡使之然也。"

-----指水滴不断地滴,可以滴穿石头;

-----比喻坚持不懈,集细微的力量也能成就难能的功劳。

----感谢读者的阅读和学习,谢谢大家。

相关推荐
AI攻城狮36 分钟前
用 Playwright 实现博客一键发布到稀土掘金
python·自动化运维
曲幽1 小时前
FastAPI分布式系统实战:拆解分布式系统中常见问题及解决方案
redis·python·fastapi·web·httpx·lock·asyncio
孟健16 小时前
Karpathy 用 200 行纯 Python 从零实现 GPT:代码逐行解析
python
码路飞18 小时前
写了个 AI 聊天页面,被 5 种流式格式折腾了一整天 😭
javascript·python
曲幽20 小时前
FastAPI压力测试实战:Locust模拟真实用户并发及优化建议
python·fastapi·web·locust·asyncio·test·uvicorn·workers
敏编程1 天前
一天一个Python库:jsonschema - JSON 数据验证利器
python
前端付豪1 天前
LangChain记忆:通过Memory记住上次的对话细节
人工智能·python·langchain
databook1 天前
ManimCE v0.20.1 发布:LaTeX 渲染修复与动画稳定性提升
python·动效
花酒锄作田2 天前
使用 pkgutil 实现动态插件系统
python