首页 > 解决方案 > 如何在 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())。

有人知道如何执行滚动脚本吗?谢谢你。

标签: javascriptc#seleniumscrollautomated-tests

解决方案


如果你想在 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;");

推荐阅读