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

查看:57
本文介绍了如何使用 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?

我可以让它跳转到一个特定的位置,例如

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")); } }

例 1)

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

例 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.

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

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();

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

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