是否可以使用Selenium WebDriver进行截图?
(注:不含硒遥控器)
是否可以使用Selenium WebDriver进行截图?
(注:不含硒遥控器)
当前回答
Java
使用RemoteWebDriver,在增加了节点的截图功能后,我将像这样存储截图:
void takeScreenShotMethod(){
try{
Thread.sleep(10000);
long id = Thread.currentThread().getId();
BufferedImage image = new Robot().createScreenCapture(new Rectangle(
Toolkit.getDefaultToolkit().getScreenSize()));
ImageIO.write(image, "jpg", new File("./target/surefire-reports/"
+ id + "/screenshot.jpg"));
}
catch( Exception e ) {
e.printStackTrace();
}
}
你可以在任何需要的地方使用这种方法。然后,我假设您可以在surefire-reports/html/custom.css中定制maven-surefire-report-plugin的样式表,以便您的报告包含到每个测试的正确截图的链接。
其他回答
是的,可以使用Selenium WebDriver对网页进行快照。
WebDriver API提供的getScreenshotAs()方法为我们做了这项工作。
语法:getScreenshotAs(OutputType<X> target)
返回类型:X
参数:target—查看OutputType提供的选项
适用性:不特定于任何DOM元素
例子:
TakesScreenshot screenshot = (TakesScreenshot) driver;
File file = screenshot.getScreenshotAs(OutputType.FILE);
有关详细信息,请参阅下面的工作代码片段。
public class TakeScreenShotDemo {
public static void main(String[] args) {
WebDriver driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.get(“http: //www.google.com”);
TakesScreenshot screenshot = (TakesScreenshot) driver;
File file = screenshot.getScreenshotAs(OutputType.FILE);
// Creating a destination file
File destination = new File(“newFilePath(e.g.: C: \\Folder\\ Desktop\\ snapshot.png)”);
try {
FileUtils.copyFile(file, destination);
} catch (IOException e) {
e.printStackTrace();
}
}
}
访问Snapshot using WebDriver获取更多详细信息。
Java
String yourfilepath = "E:\\username\\Selenium_Workspace\\foldername";
// Take a snapshort
File snapshort_file = ((TakesScreenshot) mWebDriver)
.getScreenshotAs(OutputType.FILE);
// Copy the file into folder
FileUtils.copyFile(snapshort_file, new File(yourfilepath));
C#
public void TakeScreenshot()
{
try
{
Screenshot ss = ((ITakesScreenshot)driver).GetScreenshot();
ss.SaveAsFile(@"D:\Screenshots\SeleniumTestingScreenshot.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
throw;
}
}
Ruby
time = Time.now.strftime('%a_%e_%Y_%l_%m_%p_%M_%S')
file_path = File.expand_path(File.dirname(__FILE__) + 'screens_shot')+'/'+time +'.png'
#driver.save_screenshot(file_path)
page.driver.browser.save_screenshot file_path
C#
using System;
using OpenQA.Selenium.PhantomJS;
using System.Drawing.Imaging;
namespace example.com
{
class Program
{
public static PhantomJSDriver driver;
public static void Main(string[] args)
{
driver = new PhantomJSDriver();
driver.Manage().Window.Size = new System.Drawing.Size(1280, 1024);
driver.Navigate().GoToUrl("http://www.example.com/");
driver.GetScreenshot().SaveAsFile("screenshot.png", ImageFormat.Png);
driver.Quit();
}
}
}
它需要NuGet包:
PhantomJS 2.0.0 硒。支持2.48.2 硒。WebDriver 2.48.2
它是用。net Framework v4.5.2测试的。