如何使用Selenium WebDriver设置浏览器客户区大小?

时间:2016-03-31 12:36:47

标签: selenium selenium-webdriver

我找到了如何在Selenium Issue Management系统中设置浏览器窗口大小(参见Browser window control #174):

Window window = driver.manage().window();
window.setPosition(new Point(0, 0));
window.setSize(new Dimension(width, height));

但是这个解决方案设置了整个窗口的大小(标题栏,书签栏,边框等),因此客户区在不同的浏览器中有不同的大小。有没有办法简单地为流行的浏览器(Chrome,FireFox,Internet Explorer,Opera和Safari)设置相同的值?如果我不需要评估JavaScript,那就太好了。

1 个答案:

答案 0 :(得分:3)

使用一块Javascipt会更容易,但是因为你没有问过:

Dimension win_size = driver.manage().window().getSize();
WebElement html = driver.findElement(By.tagName("html"));
int inner_width = Integer.parseInt(html.getAttribute("clientWidth"));
int inner_height = Integer.parseInt(html.getAttribute("clientHeight"));

// set the inner size of the window to 400 x 400 (scrollbar excluded)
driver.manage().window().setSize(new Dimension(
    win_size.width + (400 - inner_width),
    win_size.height + (400 - inner_height)
));

并使用一段Javascript以防万一:

ArrayList padding = (ArrayList)((JavascriptExecutor) driver).executeScript(
  "return [window.outerWidth-window.innerWidth, window.outerHeight-window.innerHeight];");

// set the inner size of the window to 400 x 400 (scrollbar included)
driver.manage().window().setSize(new Dimension(
    (int)(400 + (Long)padding.get(0)),
    (int)(400 + (Long)padding.get(1))
));