Selenium WebDriver 放大/缩小页面内容 [英] Selenium WebDriver zoom in/out page content

查看:87
本文介绍了Selenium WebDriver 放大/缩小页面内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 Selenium WebDriver 中更改页面缩放级别?我试过了:

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

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

但它不起作用.

推荐答案

注意 Selenium 假定缩放级别为 100%!例如,当缩放级别不同时,IE 将拒绝启动(抛出异常),因为元素定位取决于此,如果更改缩放级别,它会在错误的位置点击错误的元素.

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.

您可以使用 Keys.chord() 方法:

You can use the Keys.chord() method:

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

谨慎使用,完成后,将缩放重新设置为 100%:

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

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

<小时>

C#

(因为我意识到 C# 绑定没有 Keys.chord() 方法)

或者,您可以像这样使用高级用户交互 API(再次, Java 代码,但它应该在 C# 中工作相同):

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);

不起作用,因为在这个 sendKeys() 方法中释放了 Ctrl 键.WebElementsendKeys() 不同于 Actions.因此,我的解决方案中使用的 Keys.NULL必需的.

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.

这篇关于Selenium WebDriver 放大/缩小页面内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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