有没有办法在硒1。X或2。x来滚动浏览器窗口,以便XPath标识的特定元素在浏览器的视图中?在Selenium中有一个focus方法,但在FireFox中它似乎不能物理地滚动视图。有人有什么建议吗?

我需要这个的原因是我正在测试点击页面上的一个元素。不幸的是,除非元素是可见的,否则事件似乎无法工作。我无法控制单击元素时触发的代码,因此无法调试或修改它,因此,最简单的解决方案是将项目滚动到视图中。


当前回答

Javascript

解决方法很简单:

const element = await driver.findElement(...)
await driver.executeScript("arguments[0].scrollIntoView(true);", element)
await driver.sleep(500);

其他回答

在Selenium中,我们需要借助JavaScript执行器来滚动到一个元素或滚动页面:

je.executeScript("arguments[0].scrollIntoView(true);", element);

在上面的语句中,元素就是我们需要滚动的元素。我尝试了上面的代码,它对我有用。

我有一个完整的帖子和视频:

http://learn-automation.com/how-to-scroll-into-view-in-selenium-webdriver/

Selenium 2尝试滚动到元素,然后单击它。这是因为除非Selenium 2认为元素是可见的,否则它不会与元素交互。

滚动到元素是隐式的,所以您只需要找到项目,然后使用它。

webElement = driver.findElement(By.xpath("bla-bla-bla"));
((JavascriptExecutor)driver).executeScript("arguments[0].scrollIntoView();", webElement);

更多的例子,请点击这里。都是俄语,但Java代码是跨文化的:)

将一个元素滚动到视图中的Ruby脚本如下所示。

$driver.execute_script("arguments[0].scrollIntoView(true);", element)
sleep(3)
element.click

您可以使用org.openqa.selenium. actions类移动到一个元素。

Java:

WebElement element = driver.findElement(By.id("my-id"));
Actions actions = new Actions(driver);
actions.moveToElement(element);
actions.perform();

Python:

from selenium.webdriver.common.action_chains import ActionChains
ActionChains(driver).move_to_element(driver.sl.find_element_by_id('my-id')).perform()