如何使用C#使用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")); } }

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

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

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

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

有人看到成功By.ClassName。 有没有人知道在C#绑定中执行此操作是否有问题.Id?

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

这是原始答案: 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(); 

这适用于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 } } 

这对我有用:

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