有谁知道是否可以使用Selenium WebDriver截屏?(注:不是硒RC)
有谁知道是否可以使用Selenium WebDriver截屏?(注:不是硒RC)
Answers:
是的,有可能。以下示例是Java语言:
WebDriver driver = new FirefoxDriver();
driver.get("http://www.google.com/");
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
// Now you can do whatever you need to do with it, for example copy somewhere
FileUtils.copyFile(scrFile, new File("c:\\tmp\\screenshot.png"));
/tmp
是在其自己的文件系统上,并且FirefoxDriver将屏幕截图写入/tmp
。
HtmlUnitDriver
它没有实现TakesScreenshot
(请参阅selenium.googlecode.com/git/docs/api/java/org/openqa/selenium/…了解支持的驱动程序列表)。但是您可以另存为HTML。
org.apache.commons.io.FileUtils
每个WebDriver都有一个.save_screenshot(filename)
方法。因此,对于Firefox,可以这样使用:
from selenium import webdriver
browser = webdriver.Firefox()
browser.get('http://www.google.com/')
browser.save_screenshot('screenie.png')
令人困惑的是,.get_screenshot_as_file(filename)
还存在执行相同功能的方法。
也有以下方法:(.get_screenshot_as_base64()
用于嵌入html)和.get_screenshot_as_png()
(用于检索二进制数据)。
并且请注意,WebElement的.screenshot()
方法工作类似,但是仅捕获所选元素。
driver.set_window_size(1366, 728)
。
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;
}
}
driver.takeScreenshot().then(function(data){
var base64Data = data.replace(/^data:image\/png;base64,/,"")
fs.writeFile("out.png", base64Data, 'base64', function(err) {
if(err) console.log(err);
});
});
var1
您可以根据需要调用它。U应该查看takeScreenshot()
函数以了解其确切含义。也许是使用画布从javascript渲染的二进制图像。在呈现之前,它可以是dom。调查。
require 'rubygems'
require 'selenium-webdriver'
driver = Selenium::WebDriver.for :ie
driver.get "https://www.google.com"
driver.save_screenshot("./screen.png")
还有更多文件类型和选项可用,您可以在takes_screenshot.rb中查看
headless
和Firefox
我解决了这个问题。您可以扩充RemoteWebDriver
,以为其提供其代理驱动程序实现的所有接口:
WebDriver augmentedDriver = new Augmenter().augment(driver);
((TakesScreenshot)augmentedDriver).getScreenshotAs(...); //works this way
使用PHPUnit_Selenium扩展版本1.2.7:
class MyTestClass extends PHPUnit_Extensions_Selenium2TestCase {
...
public function screenshot($filepath) {
$filedata = $this->currentScreenshot();
file_put_contents($filepath, $filedata);
}
public function testSomething() {
$this->screenshot('/path/to/screenshot.png');
}
...
}
public Bitmap TakeScreenshot(By by) {
// 1. Make screenshot of all screen
var screenshotDriver = _selenium as ITakesScreenshot;
Screenshot screenshot = screenshotDriver.GetScreenshot();
var bmpScreen = new Bitmap(new MemoryStream(screenshot.AsByteArray));
// 2. Get screenshot of specific element
IWebElement element = FindElement(by);
var cropArea = new Rectangle(element.Location, element.Size);
return bmpScreen.Clone(cropArea, bmpScreen.PixelFormat);
}
public String captureScreen() {
String path;
try {
WebDriver augmentedDriver = new Augmenter().augment(driver);
File source = ((TakesScreenshot)augmentedDriver).getScreenshotAs(OutputType.FILE);
path = "./target/screenshots/" + source.getName();
FileUtils.copyFile(source, new File(path));
}
catch(IOException e) {
path = "Failed to capture screenshot: " + e.getMessage();
}
return path;
}
import org.openqa.selenium.OutputType as OutputType
import org.apache.commons.io.FileUtils as FileUtils
import java.io.File as File
import org.openqa.selenium.firefox.FirefoxDriver as FirefoxDriver
self.driver = FirefoxDriver()
tempfile = self.driver.getScreenshotAs(OutputType.FILE)
FileUtils.copyFile(tempfile, File("C:\\screenshot.png"))
我使用这种方法进行屏幕截图。
void takeScreenShotMethod(){
try{
Thread.sleep(10000)
BufferedImage image = new Robot().createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()));
ImageIO.write(image, "jpg", new File("./target/surefire-reports/screenshot.jpg"));
}
catch(Exception e){
e.printStackTrace();
}
}
您可以在任何需要的地方使用此方法。
似乎在这里缺失-拍摄Java中特定元素的屏幕截图:
public void takeScreenshotElement(WebElement element) throws IOException {
WrapsDriver wrapsDriver = (WrapsDriver) element;
File screenshot = ((TakesScreenshot) wrapsDriver.getWrappedDriver()).getScreenshotAs(OutputType.FILE);
Rectangle rectangle = new Rectangle(element.getSize().width, element.getSize().height);
Point location = element.getLocation();
BufferedImage bufferedImage = ImageIO.read(screenshot);
BufferedImage destImage = bufferedImage.getSubimage(location.x, location.y, rectangle.width, rectangle.height);
ImageIO.write(destImage, "png", screenshot);
File file = new File("//path//to");
FileUtils.copyFile(screenshot, file);
}
code
this.driver.manage()。window()。setSize(new Dimension(1680,1050)); 或通过CSS删除任何不需要的元素。正确的解决方案是从滚动计算y偏移。
Firefox
可以正常工作,因为它可以基于“尺寸”从完整图像中裁剪元素屏幕。在Chrome
如果该元素是在视图部分可用出从该视图部分图像滚动它捕获元件罚款。如果我们要在滚动document.documentElement.clientHeight
客户端高度两次后获取屏幕截图,请使用(location.y)-2*clientHeight
以获得确切的元素屏幕截图。感谢您的帖子对我有帮助...
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();
}
}
}
需要NuGetPackages:
使用.NETFramework v4.5.2测试
我无法获得可接受的答案来工作,但是根据当前的WebDriver文档,以下内容对OS X 10.9上的Java 7来说很适合我:
import java.io.File;
import java.net.URL;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.remote.Augmenter;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
public class Testing {
public void myTest() throws Exception {
WebDriver driver = new RemoteWebDriver(
new URL("http://localhost:4444/wd/hub"),
DesiredCapabilities.firefox());
driver.get("http://www.google.com");
// RemoteWebDriver does not implement the TakesScreenshot class
// if the driver does have the Capabilities to take a screenshot
// then Augmenter will add the TakesScreenshot methods to the instance
WebDriver augmentedDriver = new Augmenter().augment(driver);
File screenshot = ((TakesScreenshot)augmentedDriver).
getScreenshotAs(OutputType.FILE);
}
}
After do |scenario|
if(scenario.failed?)
puts "after step is executed"
end
time = Time.now.strftime('%a_%e_%Y_%l_%m_%p_%M')
file_path = File.expand_path(File.dirname(__FILE__) + '/../../../../../mlife_screens_shot')+'/'+time +'.png'
page.driver.browser.save_screenshot file_path
end
Given /^snapshot$/ do
time = Time.now.strftime('%a_%e_%Y_%l_%m_%p_%M')
file_path = File.expand_path(File.dirname(__FILE__) + '/../../../../../mlife_screens_shot')+'/'+time +'.png'
page.driver.browser.save_screenshot file_path
end
public function takescreenshot($event)
{
$errorFolder = dirname(dirname(__FILE__)) . DIRECTORY_SEPARATOR . "ErrorScreenshot";
if(!file_exists($errorFolder)){
mkdir($errorFolder);
}
if (4 === $event->getResult()) {
$driver = $this->getSession()->getDriver();
$screenshot = $driver->getWebDriverSession()->screenshot();
file_put_contents($errorFolder . DIRECTORY_SEPARATOR . 'Error_' . time() . '.png', base64_decode($screenshot));
}
}
takescreenshot
函数?具体来说,$event
变量来自哪里?我是一个完整的Selenium新手,因此非常感谢对此问题的解答,如果您不假设其先前具有Selenium知识,将不胜感激!
Set-Location PATH:\to\selenium
Add-Type -Path "Selenium.WebDriverBackedSelenium.dll"
Add-Type -Path "ThoughtWorks.Selenium.Core.dll"
Add-Type -Path "WebDriver.dll"
Add-Type -Path "WebDriver.Support.dll"
$driver = New-Object OpenQA.Selenium.PhantomJS.PhantomJSDriver
$driver.Navigate().GoToUrl("https://www.google.co.uk/")
# Take a screenshot and save it to filename
$filename = Join-Path (Get-Location).Path "01_GoogleLandingPage.png"
$screenshot = $driver.GetScreenshot()
$screenshot.SaveAsFile($filename, [System.Drawing.Imaging.ImageFormat]::Png)
其他驱动程序...
$driver = New-Object OpenQA.Selenium.Chrome.ChromeDriver
$driver = New-Object OpenQA.Selenium.Firefox.FirefoxDriver
$driver = New-Object OpenQA.Selenium.IE.InternetExplorerDriver
$driver = New-Object OpenQA.Selenium.Opera.OperaDriver
[OpenQA.Selenium.ScreenshotImageFormat]::Png
比System.Drawing
名称空间好用。
Python-Element的屏幕截图:
这是一个很老的问题,有多个答案。但是,这里似乎缺少使用Python拍摄特定Web元素的屏幕截图的功能。
位置
Web元素在页面上具有自己的位置,通常以x和y像素为单位进行度量,称为元素的(x,y)坐标。并且location对象包含两个值。
尺寸
就像位置一样,每个WebElement都具有宽度和高度。可用作尺寸对象。
使用(x,y)坐标和宽度,高度值,我们可以裁剪图像并将其存储在文件中。
from selenium import webdriver
from PIL import Image
driver = webdriver.Firefox(executable_path='[Browser Driver Path]')
driver.get('https://www.google.co.in')
element = driver.find_element_by_xpath("//div[@id='hplogo']")
location = element.location
size = element.size
driver.save_screenshot("/data/image.png")
x = location['x']
y = location['y']
width = location['x']+size['width']
height = location['y']+size['height']
im = Image.open('/data/WorkArea/image.png')
im = im.crop((int(x), int(y), int(width), int(height)))
im.save('/data/image.png')
注意:摘自 http://allselenium.info/capture-screenshot-element-using-python-selenium-webdriver/
通过多种方法 硒的 爪哇 和 蟒蛇客户截图使用硒web驱动器
以下是截屏的不同Java方法:
getScreenshotAs()
从TakesScreenshot界面使用:
代码块:
package screenShot;
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class Firefox_takesScreenshot {
public static void main(String[] args) throws IOException {
System.setProperty("webdriver.gecko.driver", "C:\\Utility\\BrowserDrivers\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("https://login.bws.birst.com/login.html/");
new WebDriverWait(driver, 20).until(ExpectedConditions.titleContains("Birst"));
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile, new File(".\\Screenshots\\Mads_Cruz_screenshot.png"));
driver.quit();
}
}
屏幕截图:
如果网页是jquery启用可以使用shot从pazone / ashot库:
代码块:
package screenShot;
import java.io.File;
import javax.imageio.ImageIO;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import ru.yandex.qatools.ashot.AShot;
import ru.yandex.qatools.ashot.Screenshot;
import ru.yandex.qatools.ashot.shooting.ShootingStrategies;
public class ashot_CompletePage_Firefox {
public static void main(String[] args) throws Exception {
System.setProperty("webdriver.gecko.driver", "C:\\Utility\\BrowserDrivers\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("https://jquery.com/");
new WebDriverWait(driver, 20).until(ExpectedConditions.titleContains("jQuery"));
Screenshot myScreenshot = new AShot().shootingStrategy(ShootingStrategies.viewportPasting(100)).takeScreenshot(driver);
ImageIO.write(myScreenshot.getImage(),"PNG",new File("./Screenshots/firefoxScreenshot.png"));
driver.quit();
}
}
屏幕截图:
使用 硒快门虫来自assertthat / selenium-shutterbug库:
代码块:
package screenShot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import com.assertthat.selenium_shutterbug.core.Shutterbug;
import com.assertthat.selenium_shutterbug.utils.web.ScrollStrategy;
public class selenium_shutterbug_fullpage_firefox {
public static void main(String[] args) {
System.setProperty("webdriver.gecko.driver", "C:\\Utility\\BrowserDrivers\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("https://www.google.co.in");
Shutterbug.shootPage(driver, ScrollStrategy.BOTH_DIRECTIONS).save("./Screenshots/");
driver.quit();
}
}
屏幕截图:
以下是截屏的不同Python方法:
使用save_screenshot()
方法:
代码块:
from selenium import webdriver
driver = webdriver.Chrome(r'C:\Utility\BrowserDrivers\chromedriver.exe')
driver.get("http://google.com")
driver.save_screenshot('./Screenshots/save_screenshot_method.png')
driver.quit()
屏幕截图:
代码块:
from selenium import webdriver
driver = webdriver.Chrome(r'C:\Utility\BrowserDrivers\chromedriver.exe')
driver.get("http://google.com")
driver.get_screenshot_as_file('./Screenshots/get_screenshot_as_file_method.png')
driver.quit()
屏幕截图:
代码块:
from selenium import webdriver
driver = webdriver.Chrome(r'C:\Utility\BrowserDrivers\chromedriver.exe')
driver.get("http://google.com")
screenPnG = driver.get_screenshot_as_png()
#Crop it back to the window size (it may be taller)
box = (0, 0, 1366, 728)
im = Image.open(BytesIO(screenPnG))
region = im.crop(box)
region.save('./Screenshots/get_screenshot_as_png_method.png', 'PNG', optimize=True, quality=95)
driver.quit()
屏幕截图:
您可以使用python网络驱动程序从Windows捕获图像。使用以下页面需要捕获屏幕截图的代码
driver.save_screenshot('c:\foldername\filename.extension(png,jpeg)')
public void captureScreenShot(String obj) throws IOException {
File screenshotFile=((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(screenshotFile,new File("Screenshots\\"+obj+""+GetTimeStampValue()+".png"));
}
public String GetTimeStampValue()throws IOException{
Calendar cal = Calendar.getInstance();
Date time=cal.getTime();
String timestamp=time.toString();
System.out.println(timestamp);
String systime=timestamp.replace(":", "-");
System.out.println(systime);
return systime;
}
使用这两种方法,您还可以对日期和时间进行截屏。
使用RemoteWebDriver,在使用截图功能扩展Node之后,我将这样存储截图:
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的样式表,以便您的报告包含指向每个测试的正确屏幕截图的链接?
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(IWebDriver driver, string path = @"output")
{
var cantakescreenshot = (driver as ITakesScreenshot) != null;
if (!cantakescreenshot)
return;
var filename = string.Empty + DateTime.Now.Hour + DateTime.Now.Minute + DateTime.Now.Second + DateTime.Now.Millisecond;
filename = path + @"\" + filename + ".png";
var ss = ((ITakesScreenshot)driver).GetScreenshot();
var screenshot = ss.AsBase64EncodedString;
byte[] screenshotAsByteArray = ss.AsByteArray;
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
ss.SaveAsFile(filename, ImageFormat.Png);
}
爪哇
在Selenium中添加TestName和Timestamp的故障中捕获屏幕截图的方法。
public class Screenshot{
final static String ESCAPE_PROPERTY = "org.uncommons.reportng.escape-output";
public static String imgname = null;
/*
* Method to Capture Screenshot for the failures in Selenium with TestName and Timestamp appended.
*/
public static void getSnapShot(WebDriver wb, String testcaseName) throws Exception {
try {
String imgpath=System.getProperty("user.dir").concat("\\Screenshot\\"+testcaseName);
File f=new File(imgpath);
if(!f.exists()) {
f.mkdir();
}
Date d=new Date();
SimpleDateFormat sd=new SimpleDateFormat("dd_MM_yy_HH_mm_ss_a");
String timestamp=sd.format(d);
imgname=imgpath+"\\"+timestamp+".png";
//Snapshot code
TakesScreenshot snpobj=((TakesScreenshot)wb);
File srcfile=snpobj.getScreenshotAs(OutputType.FILE);
File destFile=new File(imgname);
FileUtils.copyFile(srcfile, destFile);
}
catch(Exception e) {
e.getMessage();
}
}
public static void ClickButton()
{
try
{
// code
}
catch (Exception e)
{
TestReport.Setup(ReportLevel.Debug, "myReport.rxlog", true);
Report.Screenshot();
throw (e);
}
}