Please help me in saving web page as image using java.
I am using selenium web driver for an application, I need to take screenshot for an alert box.
So I thought it will be better if we have "save as image" button so that I can take the alert screenshot.
I am using firefox web driver
Newer versions of firefox having new feature of executing commands by pressing SHIFT+F2
It helped me in taking alert screenshots, I used robot object for this but not using web driver
You can simply install Firefox plugin: https://addons.mozilla.org/en-US/firefox/addon/fireshot/ and take any screenshot of web page.
This robot function will help you to take screenshot of displaying screen. You can edit it.
import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import java.io.File;
public void captureScreen(String fileName)throws Exception {
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
Rectangle screenRectangle = newRectangle(screenSize);
Robot robot = newRobot();
BufferedImage image = robot.createScreenCapture(screenRectangle);
ImageIO.write(image,"png",newFile(fileName));
}
The following may help you.
File screenShot = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
File f = new File("Location to save your image ");
Related
Am trying to take the complete page screenshot both horizontally and vertically using Firefox gecko driver and aShot Library.
However, the results are not as expected. Take a look:
driver.get("https://google.com");
Screenshot fpScreenshot = new AShot().shootingStrategy(ShootingStrategies.viewportPasting(1000)).takeScreenshot(driver);
ImageIO.write(fpScreenshot.getImage(),"JPEG",new File("FullPageScreenshot.jpg"));
Looked into a lot of variants but nothing is working. Interestingly, when I try using old firefox version (46), I am able to take full screenshot without any third party library. Am trying to use latest firefox and have full screenshot functionality.
Any help?
Try:
Screenshot screenshot = new AShot().shootingStrategy(ShootingStrategies.viewportPasting(ShootingStrategies.scaling(1.75f), 1000)).takeScreenshot(driver);
where 1.75f is device pixel ratio (you can run window.devicePixelRatio; in browser console to find it).
If it's still not capturing full screen, change it to 2f
While working with Selenium Java Client v3.12.0, ChromeDriver v2.40, Chrome v 67.0 using ashot-1.4.4.jar here is an example to take the complete page screenshot both horizontally and vertically using ChromeDriver and aShot Library of the url https://jquery.com/:
Code Block:
import java.io.File;
import javax.imageio.ImageIO;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
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 {
public static void main(String[] args) throws Exception {
System.setProperty("god.bless.you", "C:\\Utility\\BrowserDrivers\\chromedriver.exe");
ChromeOptions options = new ChromeOptions();
options.addArguments("start-maximized");
options.addArguments("disable-infobars");
options.addArguments("--disable-extensions");
WebDriver driver = new ChromeDriver(options);
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/elementScreenshot.png"));
driver.quit();
}
}
Screenshots:
Reference
You can find a detailed discussion in How to take screenshot with Selenium WebDriver
Could you please let me know how I can upload one pdf from my system into the website. Here is the example of my code, but its not working :
Driver.get("https://www.pdfunlock.com/");
Driver.manage().timeouts().implicitlyWait(1,TimeUnit.MINUTES);
Driver.findElement(By.id("fromComputer")).click();
Driver.findElement(By.id("Open")).click();
WebElement = Driver.find_element_by_id("fileUpload")
element.send_keys("C:\myfile.txt")
Please help.
Thankiew.
Selenium WebDriver operates only on browser DOM window. When you are trying to upload a file, you are intending to automate a windows level flow, which is out-of-scope for selenium. In short, you cannot use selenium in any form to upload a file.
But... you can do so, using Java's Robot API, or using an AutoIT script.
Please visit this link to learn more about AutoIt, and file uploading using it.
http://toolsqa.com/selenium-webdriver/autoit-selenium-webdriver/
To use the compiled AuoIT script in your Java code, simply use this
Runtime.getRuntime().exec(pathToTheExecutableFile);
Use Robot API to interact with Windows pop-up or Browse windows . Selenium will not be able to interact with Windows file browser.
Go through this for quick overview:
Reference Link
I am assuming you are not able to upload because you need to browse to your local location to upload to your website
try this (Only Drawback of this is you have to be on the opened browser open dialog when this code is running i.e. this code won't run in background) :
import java.awt.AWTException;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.awt.event.KeyEvent;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class Lists {
public static void main(String[] args) throws AWTException {
System.setProperty("webdriver.chrome.driver", "C:\\SeleniumDriver\\chromedriver_win32\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://www.pdfunlock.com/");
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
driver.findElement(By.xpath("//*[#id='fromComputer']")).click();
String filePath = "C:\\Users\\kushal\\Desktop\\1.pdf";
StringSelection stringSelection = new StringSelection(filePath);
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
clipboard.setContents(stringSelection, stringSelection);
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_CONTROL);
robot.keyRelease(KeyEvent.VK_V);
robot.keyPress(KeyEvent.VK_TAB);
robot.keyRelease(KeyEvent.VK_TAB);
robot.keyPress(KeyEvent.VK_TAB);
robot.keyRelease(KeyEvent.VK_TAB);
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
}
}
You can use following code (Robot API) to upload a file to website, if you are using java.
//After Open Upload window
//Copy the file path in clipboard
StringSelection ss=new StringSelection("File path");
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss, null);
//Paste your copied path in modal window using mouse events
Robot rb=new Robot();
rb.keyPress(KeyEvent.VK_CONTROL);
rb.keyPress(KeyEvent.VK_V);
rb.keyRelease(KeyEvent.VK_CONTROL);
rb.keyRelease(KeyEvent.VK_V);
rb.keyPress(KeyEvent.VK_ENTER);
rb.keyRelease(KeyEvent.VK_ENTER);
This is another question about Selenium and clicking. I have been struggling for about two days and can't get it to work - I have tried the answers in the internet and now I need a concerted effort. Thanks in Advance!!
I am working on the following site http://144.76.109.38/peTEST - this might help if you want to retrace my steps.
I am trying to fill out the login form, and then click on Login and see the answer page.
Here is my code:
import java.io.File;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.Writer;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.openqa.selenium.support.ui.Select;
public class toJava {
public static void main(String[] args) {
System.setProperty("webdriver.gecko.driver","/home/tallen/RTI/lib/geckodriver/geckodriver");
WebDriver driver = new FirefoxDriver();
driver.get("http:144.76.109.38/peTEST");
File SF2 = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
try{
FileUtils.copyFile(SF2, new File("./out-004.png"));
}catch(IOException ioe){
System.out.println("There was an IO error");
}
driver.findElement(By.id("user_login_name")).click();
WebElement WE4 = driver.findElement(By.id("user_login_name"));
WE4.sendKeys("Superuser");
driver.findElement(By.id("user_password")).click();
WebElement WE6 = driver.findElement(By.id("user_password"));
WE6.sendKeys("Jkerouac1!");
WebElement WE7 = driver.findElement(By.xpath(".//*[#type='button'][#onclick='login()'][#value='Login']"));
WE7.sendKeys(Keys.ENTER);
File SF8 = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
try{
FileUtils.copyFile(SF8, new File("./out-005.png"));
}catch(IOException ioe){
System.out.println("There was an IO error");
}
driver.quit();
}
}
So basically I am opening up the page, taking a screenshot entering the user name and password, clicking Login and then taking another screenshot.
The compile and the run on this are clean - that is no exceptions and no problems. I even get two screenshots. The first screenshot shows the login page - with no data entered. The second screenshot shows the login page filled, the button I want to click marked, but not the "welcome Page" that you would get if you successfully log in. That the screenshot shows the button marked, I know that I have found the element. I have give the login info in the script, in case you want to try it out with Selenium first.
Why is the login button not being "clicked." I have tried click, perform, etc. to no avail. I have even tried putting in implicit waits - still nothing.
I have tried to Advanced Usage Interactions - and still nothing.
I am pretty new to Selenium and Java and am hoping that it is just something stupid that I am overlooking. But after looking through the Web, the solutions there are just not helping.
I am working on Debian-70-Wheezy-64-LAMP
My Selenium Libraries are from client-combined-3.0.1-nodeps.jar
My Geckodriver is v0.11.1-linux64
Thanks for the Help!!!
Hi, I don't know if it can cause a problem but anyway for the login button I would use WE7.click(); I just think that it's easier to understand what you're trying to do with the element.
I've been working with the GeckoDriver for a while and talking with some experienced people in the area and they told me that Gecko has many problems that are not fixed yet.
They always recommended me not to use GeckoDriver because it seems to fail very often and told me to use FirefoxDriver instead.
To try it this way, and this is important, you'll just need to keep working with an older version of Firefox as the version 46 that is compatible with FirefoxDriver (that version worked for me and you can download it from places like this) and avoid using GeckoDriver.
Also the version 47 seems to work with the FirefoxDriver as I've found here.
Remember: When you install one of these previous versions of Firefox, don't forget to go to settings and disable the automatic updates and background updates because if you don't do this, you'll end soon again with the latest version that requires GeckoDriver.
In addition you can try some validation as the following:
if(WE7.isDisplayed() && WE7.isEnabled()){
WE7.click();
}
This kind of validations would help in case that the page isn't fully loaded at the moment that you're trying to take action over the web element. If the element is not ready, you will click it without errors but it just won't work
Hope this works for you too!
I wanted to import a image in java, and I have no idea how to do it. I need someone to show me how. I wanted to import a jpg image I found on google, I tried and a lot example code online but none of them works for me. The application I use for programming my code is by using eclipse. P.S I use a mac.
Given that you've tagged JPanel in your question, I'm going to assume that you're using swing. You can add an image to a JLabel like so:
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.ImageIcon;
import java.net.URL;
// inside your class constructor/method
JPanel panel = new JPanel();
ImageIcon img = new ImageIcon(new URL("http://image...."));
JLabel jlPic = new JLabel(img);
panel.add(jlPic);
If your image is on your computer instead of from a URL, you can simply pass a String path to that image to the constructor of ImageIcon instead.
I am using Selenium Webdriver(Java), i want to use IE driver for my testing, however i come up with the problem, can anyone help me out of this please, The script which are running fine in firefox fails to run in IE, I am just opening a google page and searching some word but my code only opens the google page write the keyword but unable to hit the serch button on google page using IEdriver, after too much google i found one thimg that when IE browser get opens it will opened in IE8 Compatibility view and due to this its attributes like id, name get changed as compared to FF, but when i changes this to IE8 view manually the properties are same as FF,(Press F12 key on keyboard open developers tool on IE) So can anyone please let me know how to overcome this or how to open the IE browser in IE8 mode, or anyone knows any different solution of using IE for selenium webdriver.
My code is as follows
package backOffice;
import java.io.File;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import com.gargoylesoftware.htmlunit.javascript.configuration.BrowserName;
import bsh.ParseException;
public class Time
{
private WebDriver driver;
private String baseUrl= "http://www.google.co.in/";
public static void main(String args[]) throws InterruptedException
{
Time tm=new Time();
tm.trial();
}
private void trial() throws InterruptedException
{
File file = new File("C:/Documents and Settings/Administrator/Desktop/32- bit_IEDriverServer_Win32_2.31.0/IEDriverServer.exe");
System.setProperty("webdriver.ie.driver", file.getAbsolutePath());
DesiredCapabilities caps = DesiredCapabilities.internetExplorer(); caps.setCapability("ignoreZoomSetting", true);
driver=new InternetExplorerDriver(caps);
driver.get(baseUrl + "/");
driver.findElement(By.id("gbqfq")).clear();
driver.findElement(By.id("gbqfq")).sendKeys("harshal kakade");
driver.findElement(By.id("gbqfb")).click();
driver.findElement(By.linkText("Harshal Kakade - India | LinkedIn")).click ();
}
}
Thanks,
Harshal.
try to look at the internet options -> security and uncheck "Enable Protected Mode". Probably there is the problem.