Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
731 views
in Technique[技术] by (71.8m points)

Selenium WebDriver zoom in/out page content

How to change page zoom level in Selenium WebDriver? I tried:

driver.Keyboard().pressKey(Keys.Control);
driver.Keyboard().pressKey(Keys.Add);

But it doesn't work.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Beware that Selenium assumes the zoom level is at 100%! For example, IE will refuse to start (throws an Exception) when the zoom level is different, because the element locating depends on this and if you changed the zoom level, it would click on wrong elements, at wrong places.


Java

You can use the Keys.chord() method:

WebElement html = driver.findElement(By.tagName("html"));
html.sendKeys(Keys.chord(Keys.CONTROL, Keys.ADD));

Use cautiously and when you're done, reset the zoom back to 100%:

html.sendKeys(Keys.chord(Keys.CONTROL, "0"));

C#

(since I realized C# bindings don't have the Keys.chord() method)

Or, you can use the Advanced User Interactions API like this (again, Java code, but it should work the same in C#):

WebElement html = driver.findElement(By.tagName("html"));

new Actions(driver)
    .sendKeys(html, Keys.CONTROL, Keys.ADD, Keys.NULL)
    .perform();

Again, don't forget to reset the zoom afterwards:

new Actions(driver)
    .sendKeys(html, Keys.CONTROL, "0", Keys.NULL)
    .perform();

Note that the na?ve approach

html.sendKeys(Keys.CONTROL, Keys.ADD);

doesn't work, because the Ctrl key is released in this sendKeys() method. The WebElement's sendKeys() is different from the one in Actions. Because of this, the Keys.NULL used in my solution is required.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...