使用Selenium Webdriver如何检查Web元素是否在屏幕的可见区域之外?
问题描述:
我需要检查滚动网页之前,该元素不可见.该元素实际上存在于网页上,但在屏幕上不可见.滚动网页后,该元素对用户可见.
I need to check that before scrolling the webpage the element is not visible. The element is actually present on webpage but not visible on the screen. Once I scroll the webpage, the element becomes visible to user.
如何自动实现上述方案?
How can I automate above scenario?
答
我找到了一种检查元素是否可见的方法.
I Found a way to check if the element was visible.
这个想法是获得1.页面的滚动位置; 2.浏览器可见区域的高度,以及3.元素的y位置.
The idea is to get the 1. scroll position of the page; 2. the height of the browser's visible area, and 3. the element's y-location.
scroll_position_script = """
var pageY;
if (typeof(window.pageYOffset) == 'number') {
pageY = window.pageYOffset;
} else {
pageY = document.documentElement.scrollTop;
}
return pageY;
"""
yOffset = self.browser.execute_script(scroll_position_script)
js_client_height = "return document.documentElement.clientHeight;"
browser_height = self.browser.execute_script(js_client_height)
elem_yloc = int(element.location['y'])
self.assertTrue(elem_yloc>=yOffset and elem_yloc<=yOffset+browser_height)