如何使用C#使用Selenium WebDriver滚动到元素 [英] How to scroll to element with Selenium WebDriver using C#

查看:764
本文介绍了如何使用C#使用Selenium WebDriver滚动到元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How do I get Selenium WebDriver to scroll to a particular element to get it on the screen. I have tried a lot of different options but have had no luck. Does this not work in the c# bindings?

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

I can make it jump to a particular location ex ((IJavaScriptExecutor)Driver).ExecuteScript("window.scrollTo(0, document.body.scrollHeight - 150)"); But I want to be able to send it to different elements without giving the exact location each time.

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

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

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

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

When I watch it, it does not jump down the page to the element, and the exception matches the element being off screen.

更新: 我添加了一个布尔值ex = Example.Exists();之后,检查结果. 它确实存在(正确). 它不显示(因为它仍处于屏幕外,因为它尚未移动到元素) 其未选中??????

Update: I added an bool ex = Example.Exists(); after it and checked the results. It does Exist (its true). Its not Displayed (as its still offscreen as it has not moved to the element) Its not Selected ??????

有人看到成功By.ClassName. 有人知道在c#绑定中执行By.Id是否存在问题?

Someone is seeing success By.ClassName. Does anyone know if there is a problem with doing this By.Id in the c# bindings?

推荐答案

这是一个较旧的问题,但我认为比上面建议的解决方案更好.

Its little older question, but I believe that there is better solution than suggested above.

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

您应该使用Actions类来滚动到元素.

You should use Actions class to perform scrolling to element.

var element = driver.FindElement(By.id("element-id"));
Actions actions = new Actions(driver);
actions.MoveToElement(element);
actions.Perform();

这篇关于如何使用C#使用Selenium WebDriver滚动到元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆