Вот простой javascript, который проверит, находится ли элемент в текущем окне просмотра и возвращает true / false.
function isElementInViewport(el) {
var rect = el.getBoundingClientRect();
return rect.bottom > 0 &&
rect.right > 0 &&
rect.left < (window.innerWidth || document.documentElement.clientWidth) &&
rect.top < (window.innerHeight || document.documentElement.clientHeight) ;
}
Сначала мы увидим, как это работает в консоли браузера.
- Открыть инструменты разработчика (короткая клавиша Ctrl + Shift + I)
- Скопируйте и вставьте вышеуказанную функцию javascript во вкладку консоли
- Нажмите Enter
- Теперь проверьте, отображается ли элемент
Questions
в окне просмотра на текущей странице, выполнив следующую строку
console.log (isElementInViewport (document.querySelector ("li.-item a [href = '/ questions']")));
- Вы должны увидеть
false
в выводе консоли
- Теперь прокрутите вниз до конца на этой странице
Запустите ту же строку выше
console.log (isElementInViewport (document.querySelector ( "li.-пункт
а [HREF = '/ вопросы'] ")));
На этот раз вы должны увидеть true
на выходе консоли, так как элемент виден в окне просмотра.
Теперь давайте посмотрим, как использовать это в Selenium:
// navigate to stackoverflow page
driver.get("https://stackoverflow.com/");
/* below is the javascript function that we have to run in the browser console
* If you look at the starting of the function name declaration in the javascript you see the difference
* `window.functioName = function(arg)` is the general notation when you
* want to make the javscript function available in the browser window
*/
String jsFunction = "window.isElementInViewport= function(el) {\r\n" +
" var rect = el.getBoundingClientRect();\r\n" +
" return rect.bottom > 0 &&\r\n" +
" rect.right > 0 &&\r\n" +
" rect.left < (window.innerWidth || document.documentElement.clientWidth) &&\r\n" +
" rect.top < (window.innerHeight || document.documentElement.clientHeight) ;\r\n" +
"}";
// execute the javascript function
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript(jsFunction);
// Questions Element
WebElement questionsEle = driver.findElement(By.cssSelector("li.-item a[href='\\/questions']"));
// check Questions Elements before scrolling
System.out.println(js.executeScript("return isElementInViewport(arguments[0])", questionsEle));
// Scroll to element
js.executeScript("arguments[0].scrollIntoView();", questionsEle);
// check Questions Elements after scrolling
System.out.println(js.executeScript("return isElementInViewport(arguments[0])", questionsEle));
Вот и все, теперь вы можете перенести это простое решение на вашу проблему.