使用Selenium和C#语法如何滚动到屏幕上看不到的元素?

huangapple go评论128阅读模式
英文:

How to scroll to an element that is not visible on the screen, with Selenium and using C# syntax?

问题

我想要滚动到页面中间的一个元素,但在导航到页面后,该元素在屏幕上不可见。

我的测试是使用C#语言的Selenium编写的。

任何建议都会很感激。谢谢!

我尝试使用Actions类来滚动到元素,但这似乎不起作用,可能是因为元素在没有滚动的情况下在屏幕上不可见。

是否使用JavaScriptExecutor像这样滚动是一个好方法吗?

IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
js.ExecuteScript("arguments[0].scrollIntoView();", element);

然后,我应该使用Actions类的正常滚动方式吗?

Actions actions = new Actions(driver);
actions.MoveToElement(element);
actions.Perform();
英文:

I want to scroll to and element that is in the middle of the screen but not visible on the screen after navigating to the page.
My tests are written with Selenium using C# language.
Any advice is appreciated. Thanks!

I have tried to scroll to the element using class Actions but that doesn't work, probably because the element is not visible on the screen without scrolling.

Is a good approach to scroll using JavaScriptExecutor like this?

> IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
> js.ExecuteScript("arguments[0].scrollIntoView();", element);

And after this should I use the normal way of scrolling using Actions class?

> Actions actions = new Actions(driver);
> actions.MoveToElement(element);
> actions.Perform();

答案1

得分: 0

使用scrollIntoView() 绝对是将元素置于视口中的最佳方法。

然而,在尝试滚动 元素之前,您需要引入WebDriverWait 来等待ElementIsVisible(),如下所示:

IWebElement element = new WebDriverWait(driver, TimeSpan.FromSeconds(10)).Until(ExpectedConditions.ElementIsVisible(By.XPath("ElementXPath")));
IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
js.ExecuteScript("arguments[0].scrollIntoView();", element);
英文:

Using scrollIntoView() is definitely the best approach to bring the element within the Viewport.

However, before you attempt to scroll the element you need to induce WebDriverWait for the ElementIsVisible() as follows:

IWebElement element = new WebDriverWait(driver, TimeSpan.FromSeconds(10)).Until(ExpectedConditions.ElementIsVisible(By.XPath("ElementXPath")));
IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
js.ExecuteScript("arguments[0].scrollIntoView();", element);

huangapple
  • 本文由 发表于 2023年3月15日 19:36:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/75744161.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定