Am trying to save .html page into my desktop using selenium .
Can anyone pls help?
You can use the Advanced User Interactions API:
new Actions(driver)
.sendKeys(Keys.chord(Keys.CONTROL, "s"))
.perform();
This will open the Save As dialog in which you then need to navigate manually / using the Java's Robot class:
Robot robot = new Robot();
// press Ctrl+S the Robot's way
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_S);
robot.keyRelease(KeyEvent.VK_CONTROL);
robot.keyRelease(KeyEvent.VK_S);
// press Enter
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
Presses Ctrl+S, Enter. Beware that will not work on every system and/or browser.
JavascriptExecutor js = (JavascriptExecutor) driver;
String base64string = (String) js.executeScript("var c = document.createElement('canvas');"
+ " var ctx = c.getContext('2d');"
+ "var img = document.getElementsByTagName('img')[0];"
+ "c.height=img.naturalHeight;"
+ "c.width=img.naturalWidth;"
+ "ctx.drawImage(img, 0, 0,img.naturalWidth, img.naturalHeight);"
+ "var base64String = c.toDataURL();"
+ "return base64String;");
String[] base64Array = base64string.split(",");
String base64 = base64Array[base64Array.length - 1];
byte[] data = Base64.decode(base64);
ByteArrayInputStream memstream = new ByteArrayInputStream(data);
BufferedImage saveImage = ImageIO.read(memstream);
ImageIO.write(saveImage, "png", new File("path"));
Related
I have added robot class to drag from left to right in the frame but it is not working I also use action builder drag and drop it is not working somehow I use robot class so it clicks on the header but does not do drag and drop
Here is my code :
WebDriverWait waitDrag = new WebDriverWait(driver, Duration.ofSeconds(30));
waitDrag.until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.xpath("//*[#id=\"root\"]/div/div/div[2]/div[2]/div/div[1]/div[2]/div/div[1]/div/div/div/div[1]/div")));
WebElement fromWebElement =driver.findElement(By.xpath("//*[#id=\"root\"]/div/div/div[2]/div[2]/div/div[1]/div[2]/div/div[1]/div/div/div/div[1]/div"));
WebElement toWebElement = driver.findElement(By.xpath("//div[#class=\"react-flow__pane\"]"));
Point coordinates1 = fromWebElement.getLocation();
Point coordinates2 = toWebElement.getLocation();
Robot robot = new Robot();
robot.mouseMove(coordinates1.getX(), coordinates1.getY());
robot.mousePress(InputEvent.BUTTON1_MASK);
robot.mouseMove(coordinates2.getX(), coordinates2.getY());
robot.mouseRelease(InputEvent.BUTTON1_MASK);
Thread.sleep(2000);
I'm trying to get Whatsapp QR with Selenium WebDriver on remote machine.
I using latest version on docker package
selenium/standalone-chrome:latest
The point is, if I try the following code without headless on, works smooth.
Maybe my configuration isnt correct.
Any ideas?
ChromeOptions dCap = new ChromeOptions();
dCap.setHeadless(true);
dCap.setCapability("platform", "LINUX");
dCap.setCapability("version", "latest");
dCap.addArguments("disable-infobars");
dCap.addArguments("--start-maximized");
dCap.addArguments("--disable-extensions");
dCap.addArguments("--disable-gpu");
dCap.addArguments("--window-size=1920x1080");
dCap.addArguments("--enable-javascript");
String driverPath = System.getProperty("user.dir") + "/exe/chromedriver";
System.setProperty("webdriver.chrome.driver", driverPath);
URL rutaProxy = new URL("http://localhost:4444/wd/hub");
WebDriver driver = new RemoteWebDriver(rutaProxy, dCap);
driver.get("https://web.whatsapp.com/");
WebDriverWait espera = new WebDriverWait(driver, 20);
espera.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector(".landing-main canvas")));
WebElement canvas = driver.findElement(By.cssSelector(".landing-main canvas"));
JavascriptExecutor js = (JavascriptExecutor)driver;
String imagenBase64 = (String) js.executeScript("return arguments[0].toDataURL('image/png').substring(21);", canvas);
//TEST
byte[] imageByte = Base64.getDecoder().decode(imagenBase64.substring(1));
ByteArrayInputStream bis = new ByteArrayInputStream(imageByte);
BufferedImage image = ImageIO.read(bis);
bis.close();
File outputfile = new File("image.png");
ImageIO.write(image, "png", outputfile);
driver.close();
I've been in this situation, add more time delay between a action and a window popup, because the refresh of some DOM elements takes time. Enabling headless requires more latency than not enabling it.
I'm trying to take screenshots of a video using Selenium and Java. It works fine when I use headed Chrome, but when I want to make it headless a "java.awt.image.RasterFormatException: (y + height) is outside of Raster" is thrown in
getSubimage(point.getX(), point.getY(), eleWidth, eleHeight);
Here's the code:
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.addArguments("--headless");
chromeOptions.addArguments("--start-maximized");
WebDriver driver = new ChromeDriver(chromeOptions);
// Get URL and find image
driver.get("https://www.webcamtaxi.com/en/netherlands/north-holland/purmerend-traffic-cam.html");
Thread.sleep(5000);
while (true) {
WebElement ele = driver.findElement(By.id("insideCam"));
// Get entire page screenshot
File screenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
BufferedImage fullImg = ImageIO.read(screenshot);
// Get the location of element on the page
Point point = ele.getLocation();
// Get width and height of the element
int eleWidth = ele.getSize().getWidth();
int eleHeight = ele.getSize().getHeight();
// Crop the entire page screenshot to get only element screenshot
BufferedImage eleScreenshot = fullImg.getSubimage(point.getX(), point.getY(), eleWidth, eleHeight);
ImageIO.write(eleScreenshot, "png", screenshot);
}
Does someone know how to fix this?
I have a pdf file (obtained from a byte[] generated by iText) I need to send to a signature hardware.
Due some incompatibility with the java printer driver I can't send the PDF directly, so i need to convert it to images before. I've succeed converting each PDF page to a jpg file, but customer does not like solution cause signatures are not in all the document, only in individual pages.
As I've not found any free library, I decided to make it in four steps:
STEP1: generate PDF with itext and persist it.
FileOutputStream fos = new FileOutputStream("tempFile.pdf");
fos.write(myByteArray);
fos.close();
fos.flush();
STEP 2: convert from PDF multipaged to List<java.awt.Image>
List<Image> images = null;
Ghostscript.getInstance(); // create gs instance
PDFDocument lDocument = new PDFDocument();
lDocument.load(new File("tempFile.pdf"));
SimpleRenderer renderer = new SimpleRenderer();
renderer.setResolution(300);
try
{
images = renderer.render(lDocument);
}
catch (RendererException | DocumentException e)
{
e.printStackTrace();
}
Step 3: Now I iterate over List<java.awt.Image> to convert to an individual TIFF's.
int filename = 1;
TIFFEncodeParam params = new TIFFEncodeParam();
Iterator<Image> imageIterator = images.iterator();
while (imageIterator.hasNext()) {
BufferedImage image = (BufferedImage) imageIterator.next();
FileOutputStream os = new FileOutputStream(/*outputDir + */ filename + ".tif");
JAI.create("encode", image , os, "TIFF", params);
filename ++;
}
STEP 4: create multipaged TIFF from various individual TIFF files
BufferedImage image[] = new BufferedImage[paginas];
for (int i = 0; i < paginas; i++) {
SeekableStream ss = new FileSeekableStream((i + 1) + ".tif");
ImageDecoder decoder = ImageCodec.createImageDecoder("tiff", ss, null);
PlanarImage pi = new NullOpImage(decoder.decodeAsRenderedImage(0),null,null,OpImage.OP_IO_BOUND);
image[i] = pi.getAsBufferedImage();
ss.close();
}
TIFFEncodeParam params = new TIFFEncodeParam();
params.setCompression(TIFFEncodeParam.COMPRESSION_DEFLATE);
OutputStream out = new FileOutputStream(nombre +".tif");
ImageEncoder encoder = ImageCodec.createImageEncoder("tiff", out, params);
List <BufferedImage>list = new ArrayList<BufferedImage>(image.length);
for (int i = 1; i < image.length; i++) {
list.add(image[i]);
}
params.setExtraImages(list.iterator());
encoder.encode(image[0]);
out.close();
System.out.println("Done.");
DONE. Hope that helps for someone else with same problem.
I had same issue a while ago. I got lot of help from here:
Multiple page tif
Allso check:
JAI (Java Advance Image)
Here is the conde snippet to convert pdf pages to png images (using org.apache.pdfbox library):
PDDocument document = null;
document = PDDocument.load(pdf1);
int pageNum = document.getNumberOfPages();
PDFImageWriter writer = new PDFImageWriter();
String filename = pdf1.getPath() + "-";
filename = filename.replace(".pdf", "");
writer.writeImage(document, "png", "", 1, Integer.MAX_VALUE, filename);
document.close();
And after that i converted each PNG image to TIFF and then from multiple TIFF images to single multi paged TIFF.
How to simulate Print screen button using selenium web driver in Java
Regards,
Vignesh
selenium doesn't support it, only web page shots. However you can use Robot to do it
try {
String format = "jpg";
String fileName = printScreen." + format;
Rectangle screenRect = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
Robot robot = new Robot();
BufferedImage screenFullImage = robot.createScreenCapture(screenRect);
ImageIO.write(screenFullImage, format, new File(fileName));
} catch (AWTException | IOException ex) {
System.err.println(ex);
}
And in C#
using System.Drawing;
using System.Drawing.Imaging;
using System.Windows.Forms;
Bitmap bitmap = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);
Graphics graphics = Graphics.FromImage(bitmap);
graphics.CopyFromScreen(0, 0, 0, 0, bitmap.Size);
bitmap.Save(#"C:\ScreenShots\printScreen.jpg", ImageFormat.Jpeg);