如何使用C#滚动到Selenium WebDriver的元素

mer*_*rua 22 c# selenium selenium-chromedriver selenium-webdriver

如何让Selenium WebDriver滚动到特定元素以在屏幕上显示它.我尝试了很多不同的选择,但没有运气.这不适用于c#绑定吗?

我可以让它跳转到特定的位置ex ((IJavaScriptExecutor)Driver).ExecuteScript("window.scrollTo(0, document.body.scrollHeight - 150)"); 但是我希望能够将它发送到不同的元素,而不是每次都给出确切的位置.

public IWebElement Example { get { return Driver.FindElement(By.Id("123456")); } }

例1) ((IJavaScriptExecutor)Driver).ExecuteScript("arguments[0].scrollIntoView(true);", Example);

例2) ((IJavaScriptExecutor)Driver).ExecuteScript("window.scrollBy(Example.Location.X", "Example.Location.Y - 100)");

当我观看它时,它不会将页面跳转到元素,并且异常与屏幕外的元素匹配.

更新:我添加了一个bool ex = Example.Exists(); 之后检查结果.它确实存在(它是真的).它没有显示(因为它仍然在屏幕外,因为它没有移动到元素)它没有被选中??????

有人看到成功By.ClassName.有没有人知道这样做是否有问题By.Id在c#绑定中?

DRA*_*RAX 43

这是一个较旧的问题,但我相信有比上面提出的更好的解决方案.

这是原始答案:https://stackoverflow.com/a/26461431/1221512

您应该使用Actions类来执行向元素的滚动.

var element = driver.FindElement(By.id("element-id"));
Actions actions = new Actions(driver);
actions.MoveToElement(element);
actions.Perform();
Run Code Online (Sandbox Code Playgroud)

  • 谢谢,这对我来说很棒。我从来没有真正注意过动作,但是最近又出现了几次。我真的应该更多地了解它们。 (2认同)

mil*_*nio 18

这适用于Chrome,IE8和IE11:

public void ScrollTo(int xPosition = 0, int yPosition = 0)
{
    var js = String.Format("window.scrollTo({0}, {1})", xPosition, yPosition);
    JavaScriptExecutor.ExecuteScript(js);
}

public IWebElement ScrollToView(By selector)
{
    var element = WebDriver.FindElement(selector);
    ScrollToView(element);
    return element;
}

public void ScrollToView(IWebElement element)
{
    if (element.Location.Y > 200)
    {
        ScrollTo(0, element.Location.Y - 100); // Make sure element is in the view but below the top navigation pane
    }

}
Run Code Online (Sandbox Code Playgroud)

  • 谢谢,这有效!ScrollTo() 函数的 C# 版本: `IJavaScriptExecutor js = (IJavaScriptExecutor)driver;` `js.ExecuteScript(String.Format("window.scrollTo({0}, {1})", xPosition, yPosition));` (3认同)

use*_*429 10

这对我有用:

var elem = driver.FindElement(By.ClassName("something"));
driver.ExecuteScript("arguments[0].scrollIntoView(true);", elem);
Run Code Online (Sandbox Code Playgroud)