[英]How to check if an element is into view using Selenium WebDriver?
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.要检查元素是否在视图中,
isDisplayed()
没有帮助,因为无论元素是否在视图中,它都会返回 true。
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 .要与元素交互,该元素需要位于Viewport 内。 If the element is not within the Viewport you have to
scroll()
as follows:如果元素不在视口内,则必须按如下方式
scroll()
:
((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
您可以在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:最后,在极少数情况下,如果HTML DOM包含Angular或React元素,您甚至可能必须在尝试滚动之前引入WebDriverWait以获取
visibilityOfElementLocated()
,如下所示:
((JavascriptExecutor)driver).executeScript("arguments[0].scrollIntoView();", new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("button.nsg-button"))));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.