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

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


当前回答

如果该对象传递无效:

等待浏览器。executeScript("arguments[0]. scrollintoview()",等待浏览器。(等到。elementLocated(通过。xpath(“/ / div [@jscontroller = ' MC8mtf '] ")), 1000));

有一个演示滚动到麦克风按钮,在谷歌页面。通过javascript xpath找到它,使用chromedriver和selenium-webdriver。

Start1()在狭窄的窗口中启动浏览器,麦克风按钮不显示。

Start2()在狭窄的窗口中启动浏览器,然后滚动到麦克风按钮。

require('chromedriver');
const { Builder, 
        By, 
        Key, 
        until
      }                = require('selenium-webdriver');

async function start1()  {

  var browser = new Builder()
                    .forBrowser( 'chrome' )
                    .build();
  await browser
        .manage()
        .window()
        .setRect( { width: 80, 
                    height: 1040, 
                    x:-10, 
                    y:0} 
                );
  await browser.navigate().to( "https://www.google.com/" );
}

async function start2()  {

  var browser = new Builder()
                    .forBrowser( 'chrome' )
                    .build();
  await browser
        .manage()
        .window()
        .setRect( { width: 80, 
                    height: 1040, 
                    x:-10, 
                    y:0} 
                );
  await browser.navigate().to( "https://www.google.com/" );
  await browser.executeScript( "document.evaluate(\"//div[@jscontroller='MC8mtf']\", document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.scrollIntoView(true);");
}

start1();
start2();

其他回答

在滚动的大多数情况下,这段代码都是有效的。

WebElement element = driver.findElement(By.xpath("xpath_Of_Element"));                 
js.executeScript("arguments[0].click();",element);
JavascriptExecutor js = (JavascriptExecutor) driver;
        js.executeScript("javascript:window.scrollBy(250,350)");

你可能想试试这个。

下面是我如何用PHP webDriver for Selenium做到这一点。它适用于Selenium独立服务器2.39.0 + https://github.com/Element-34/php-webdriver + Firefox 25.0

$element=$session->welement("xpath", "//input[@value='my val']");
$element->click();
$element=$session->welement("xpath", "//input[@value='ma val2']");
$element->location_in_view(); // < -- this is the candy
$element->click();

注意:我使用了Element34 php webdriver的定制版本。但是核心没有任何变化。我只是用了“welement”而不是“element”。但这对本案没有任何影响。驱动程序作者说:“允许几乎所有的API调用都是WebDriver协议本身定义的直接转换。”所以你使用其他编程语言应该没有问题。

在我的设置中,只是单击将不起作用。它将做滚动而不是点击,所以我不得不点击两次而没有调用“location_in_view()”。

注意:此方法适用于可以查看的元素,例如input类型为button。

来看看: http://code.google.com/p/selenium/wiki/JsonWireProtocol#/session/:sessionId/element/:id/location

jsonwireprotocol#的描述建议使用location + moveto,因为location _in_view是一个内部方法。

OpenQA。c#中的硒:

WebDriver.ExecuteJavaScript("arguments[0].scrollIntoView({block: \"center\", inline: \"center\"});", Element);

其中WebDriver是新的ChromeDriver(选项)或类似。

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

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