javascript - 如何在 C# 中使用 Selenium 驱动程序向上/向下滚动页面?
问题描述
我正在尝试在自动化测试环境中向上滚动窗口,但这不起作用(控制台中也没有错误):
public void ScrollToTheTop()
{
if (this.driver is RemoteWebDriver remoteDriver)
{
IJavaScriptExecutor jex = remoteDriver;
jex.ExecuteScript("window.scrollTo(0,0)");
}
}
现在如果我尝试执行jex.ExecuteScript("alert('Something')")
它工作正常,这意味着 js 得到正确执行。但由于某种原因,滚动操作不起作用(也尝试过scrollBy()
)。
有人知道如何执行滚动脚本吗?谢谢你。
解决方案
如果你想在 C# 中滚动,使用 ExecuteScript 请使用以下代码:
((IJavaScriptExecutor)Driver).ExecuteScript("window.scrollTo(0, Y)");
哪里Y
应该是垂直轴。
向下滚动:
((IJavaScriptExecutor)Driver).ExecuteScript("window.scrollTo(0, 200)");
或向上滚动:
((IJavaScriptExecutor)Driver).ExecuteScript("window.scrollTo(0, -200)");
要移动到C#-Selenium 绑定中的特定 Web 元素 :
IWebElement e = Driver.FindElement(By.XPath(xpath of the web element));
((IJavaScriptExecutor)Driver).ExecuteScript("arguments[0].scrollIntoView(true);", e);
移动到页面末尾:
((IJavaScriptExecutor)Driver).ExecuteScript("var scrollingElement = (document.scrollingElement || document.body);scrollingElement.scrollTop = scrollingElement.scrollHeight;");
推荐阅读
- excel - 在 Excel 中输入军用时间,不带“:”
- mongodb - 为什么 ReactRouter 的 Route 路径 ":params" 在 express 中读为 "styles.css"?
- c# - 为什么我的后台工作人员在使用 Task.Delay 时会死锁?
- mysql - 将图像插入 SQL 表:插入语句中的语法错误
- ubuntu - 在 Ubuntu 上安装 GitLab:“无法解析主机:packages.gitlab.com”
- python - 为什么 Raspberry Pi 中带有 arduPi 库的 Arduino 代码不起作用?
- quectel - BG95 无法激活 - AT+QIACT=1 返回错误
- regex - Powershell中的多行正则表达式查找失败
- c++ - 如何在 C++ 中访问子类
- c++ - C ++在两个分离的线程之间共享非阻塞队列和互斥锁