Verification of Element in Viewport in Selenium

后端 未结 2 1126
不思量自难忘°
不思量自难忘° 2020-12-03 16:10

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

I\'ve tried with the below code, but Point object(Y value) retu

2条回答
  •  忘掉有多难
    2020-12-03 16:38

    Thanks Florent B. Converted to python:

    def is_element_visible_in_viewpoint(driver, element) -> bool:
        return driver.execute_script("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)
    

提交回复
热议问题