如何使用 Selenium WebDriver 检查元素是否进入视图? [英] How to check if an element is into view using Selenium WebDriver?

查看:34
本文介绍了如何使用 Selenium WebDriver 检查元素是否进入视图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须检查一个元素是否在视图中,如果没有,然后使用以下方法将其滚动到视图中,然后与它进行交互 -

((JavascriptExecutor)driver).executeScript("arguments[0].scrollIntoView();", element);

如果一个元素在视图中,不要执行上面的命令.要检查元素是否在视图中,isDisplayed() 没有帮助,因为无论元素是否在视图中,它都返回 true.

您能否建议什么有助于实现检查元素是否在视图中?

解决方案

要与元素交互,该元素需要位于 视口.如果元素不在 Viewport 内,您必须 scroll() 如下:

((JavascriptExecutor)driver).executeScript("arguments[0].scrollIntoView();", element);

<块引用>

您可以在 不同的滚动选项之间有什么区别?

<小时>

此时值得一提的是,以下方法:

将在执行之前自动滚动视口中的元素.

<块引用>

您可以在 Selenium python 中找到详细讨论错误:元素无法滚动到视图中

<小时>

最后,在极少数情况下,如果 HTML DOM 包括AngularReact 元素,您甚至可能必须在尝试按如下方式滚动之前为 visibilityOfElementLocated() 引入 WebDriverWait:

((JavascriptExecutor)driver).executeScript("arguments[0].scrollIntoView();", new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("button.nsg-按钮"))));

I have to check if an element is in view and if not, only then scroll it into view using following and then interact with it -

((JavascriptExecutor)driver).executeScript("arguments[0].scrollIntoView();", element);

If an element is in view, don't execute above command. To check if an element is in view, isDisplayed() is not helping because it returns true irrespective of an element is in view or not.

Can you please suggest what will help to achieve to check if an element is in view?

解决方案

To interact with an element the element needs to be within the Viewport. If the element is not within the Viewport you have to scroll() as follows:

((JavascriptExecutor)driver).executeScript("arguments[0].scrollIntoView();", element);

You can find a detailed discussion on different scrolling option in What is the difference between the different scroll options?


At this point it is worth to mention, the following methods:

will automatically scroll the element within the Viewport before getting executed.

You can find a detailed discussion in Selenium python Error: element could not be scrolled into view


Finally, in the rarest of the rare cases if the HTML DOM comprises of Angular or React elements you may even have to induce WebDriverWait for the visibilityOfElementLocated() before you attempt to scroll as follows:

((JavascriptExecutor)driver).executeScript("arguments[0].scrollIntoView();", new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("button.nsg-button"))));

这篇关于如何使用 Selenium WebDriver 检查元素是否进入视图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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