Selenium WebDriver放大/缩小页面内容 [英] Selenium WebDriver zoom in/out page content
问题描述
如何在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.
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()
方法)
C#
(since I realized C# bindings don't have the Keys.chord()
method)
或者,您可以像这样使用高级用户交互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 键. WebElement
的sendKeys()
与
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屋!