硒视域中元素的验证 [英] Verification of Element in Viewport in Selenium

查看:179
本文介绍了硒视域中元素的验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何验证元素在视口中是否可见(浏览器的可见性)或不使用Selenium?

How to verify whether an element is visible in viewport(visibility of browser) or not using Selenium?

我尝试使用下面的代码,但是Point对象(Y值)在页面可滚动时返回巨大的值。这里有元素维度,位置和浏览器维度以及比较它们。

I've tried with the below code, but Point object(Y value) returns huge value as page is scrollable. Here am getting element dimensions, location and Dimensions of Browser and comparing them.

Dimension weD = element.getSize(); //to get the element Dimensions
Point weP = element.getLocation(); // getting the location of the element in the page.

Dimension d = driver.manage().window().getSize(); // To get the browser dimensions
int x = d.getWidth(); //browser width
int y = d.getHeight(); //browser height
int x2 = weD.getWidth() + ewp.getX();
int y2 = weD.getHeight() + ewp.getY();
return x2 <= x && y2 <= y; 

如果有人参与其中,你能否分享一下解决方案?

If anyone has worked on it, Could you please share the solution?

推荐答案

直接通过API无法实现,因此您必须使用脚本注入。

It's not possible directly via the API, so you'll have to use a script injection.

确定元素在视口中是否可见的最佳方法是使用 document.elementFromPoint 。如果它不在视口内,则返回null,如果不是,则返回子元素。

The best way to determine if an element is visible in the viewport is to get the element at the supposed location with document.elementFromPoint. It returns null if it's not within the viewport and your element or a descendant if it is.

public static Boolean isVisibleInViewport(WebElement element) {
  WebDriver driver = ((RemoteWebElement)element).getWrappedDriver();

  return (Boolean)((JavascriptExecutor)driver).executeScript(
      "var elem = arguments[0],                 " +
      "  box = elem.getBoundingClientRect(),    " +
      "  cx = box.left + box.width / 2,         " +
      "  cy = box.top + box.height / 2,         " +
      "  e = document.elementFromPoint(cx, cy); " +
      "for (; e; e = e.parentElement) {         " +
      "  if (e === elem)                        " +
      "    return true;                         " +
      "}                                        " +
      "return false;                            "
      , element);
}

这篇关于硒视域中元素的验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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