硒滚动元素进入(中心)视图 [英] selenium scroll element into (center of) view

查看:72
本文介绍了硒滚动元素进入(中心)视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当元素在硒的作用下看不见并且试图与之交互时,硒通常会先隐式滚动该元素使其进入视图.这很不错,除了令人讨厌的是,它通常只将元素放入视图中.我的意思是,如果元素在窗口下方,它将向下滚动直到元素正好与窗口边缘接壤为止.

When an element is out of view with selenium and one tries to interact with it, selenium will usually scroll the element into view first implicitly. This is great except that what is annoying is that it usually puts in the element just enough into view. What I mean is that if the element is below the window, it will scroll down enough just till when the element is just bordering the edge of the window.

通常这很好,但是当在带有边框的网站上工作时,这将导致许多此类错误

Usually this is fine, but when working on a web site with borders around it, this will lead to numerous of these kinds of errors

Selenium::WebDriver::Error::UnknownError:
       unknown error: Element is not clickable at point (438, 747). Other element would receive the click: <body>...</body>

因为通常网页的边框位于其上方,但是无论如何都会尝试单击该元素.反正有处理吗?也许在看不见时自动将元素移动到屏幕中心?我正在考虑通过红宝石修补猴子.

Because usually the border of the web page is over it, but will try to click the element anyway. Is there anyway handle this? perhaps to automatically move elements to the center of the screen when out of view? I am thinking along the lines monkey-patching via ruby.

推荐答案

这应该可以将元素滚动到视图中心:

This should work in order to scroll element into center of view:

WebElement element = driver.findElement(By.xxx("xxxx"));

String scrollElementIntoMiddle = "var viewPortHeight = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);"
                                            + "var elementTop = arguments[0].getBoundingClientRect().top;"
                                            + "window.scrollBy(0, elementTop-(viewPortHeight/2));";

((JavascriptExecutor) driver).executeScript(scrollElementIntoMiddle, element);

这篇关于硒滚动元素进入(中心)视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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