使用 Selenium WebDriver 获取网页的全页截图
使用 Selenium WebDriver 进行全页截图。
在执行测试用例时,如果测试用例失败,我们需要截取页面截图以便进行错误报告。这也可以使用 Selenium Webdriver 来完成。
我们可以使用以下语法来捕获并保存完整页面的截图。
File screenshot = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
然后可以使用以下语法将其存储在本地驱动器中
FileUtils.copyFile(screenshot, new File(“D:\\screenshot.png”));
现在,这里是一个小的 webdriver 脚本示例,我们可以用它来捕获完整页面的截图。
package Screenshot;
import java.io.File;
import java.util.concurrent.TimeUnit;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class FullPage_Screenshot {
public static void main(String[] args) throws Exception {
WebDriver driver = new FirefoxDriver();
try{
driver.get("http://google.co.in");
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
driver.manage().window().maximize();
//driver.findElement(By.xpath("//input[@id='gbqfq']")).sendKeys("test");
driver.findElement(By.xpath("//input[@id='gbqfq1']")).sendKeys("test");
System.out.println("Entered data in textfield");
}
catch (Exception e)
{
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile, new File("D:\\screenShot1.png"));
System.out.println("Screenshot is captured for failed testcase");
}
}
}
// driver.findElement(By.xpath(“//input[@id='gbqfq']“)).sendKeys(“test”);
如果我们执行此语句,则可以向文本字段中输入数据,并且测试用例将通过。因此,它不会截取截图。
因此,我已经注释掉了正确的语句,以便测试用例失败并捕获截图。
希望这能帮到你。 :)