英文:
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);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论