I am trying to capture simple screenshot using phantomjs for https://www.google.com . Screenshot is coming as blank . I am using eclipse in windows and jars phantomjsdriver1.1 , selenium jars all 2.39 version .
When I mention site as http://google , it redirects to https and captures screenshot . But I need it to exclusively capture it for https only . Below is my code . Thanks in advance .
import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import net.anthavio.phanbedder.Phanbedder;
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.phantomjs.PhantomJSDriver;
import org.openqa.selenium.phantomjs.PhantomJSDriverService;
import org.openqa.selenium.remote.DesiredCapabilities;
public class Schedule {
public static void main(String[] args) {
File phantomjs = Phanbedder.unpack();
DesiredCapabilities dcaps = new DesiredCapabilities();
dcaps.setCapability(PhantomJSDriverService.PHANTOMJS_EXECUTABLE_PATH_PROPERTY, phantomjs.getAbsolutePath());
dcaps.setCapability("takesScreenshot", true);
String [] phantomJsArgs = {"---ignore-ssl-errors=yes"};
dcaps.setCapability(
PhantomJSDriverService.PHANTOMJS_GHOSTDRIVER_CLI_ARGS,
phantomJsArgs);
PhantomJSDriver driver = new PhantomJSDriver(dcaps);
driver.get("https://www.google.com");
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
try {
FileUtils.copyFile(scrFile, new File("C:\\Users\\Desktop\\fci\\sample.jpeg"),true);
} catch (IOException e) {
System.out.println("exception");
}
System.out.println("Page title is: " + driver.getTitle());
driver.quit();
}
}
PhantomJS is a headless browser meaning; you don't get to see what is happening; everything that's done is done in background.
Related
My application will download a file when clicking on a button.
The file will download POST submit and there is no way to get the URL of the file before submitting it.
I am looking for a way to download POST request attachment using selenium. Can someone guide me on how to achieve this using selenium Java?.
I am not certain of your exact use case, but would something like this work? I made this example to download the Google Chrome.exe automatically. Like with your file, there is no direct link to it either but rather just a download generated by the website.
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.chrome.ChromeOptions;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
public class Main {
public static void main(String[] args) {
ChromeOptions options = new ChromeOptions();
System.setProperty("webdriver.chrome.driver","where your ChromeDriver lives");
Map<String, Object> prefs = new HashMap<String, Object>();
prefs.put("download.default_directory", "where you want the file to be downloaded");
prefs.put("download.prompt_for_download", false);
options.setExperimentalOption("prefs", prefs);
WebDriver driver = new ChromeDriver(options);
String baseUrl = "https://www.google.com/chrome/";
driver.get(baseUrl);
try {
TimeUnit.SECONDS.sleep(5);
} catch(Exception e){
}
List<WebElement> targetsWithClass = driver.findElements(By.className("chr-cta__button--blue"));
targetsWithClass.get(1).click();
try {
TimeUnit.SECONDS.sleep(3);
} catch(Exception e){
}
driver.findElement(By.id("js-accept-install")).click();
}
}
I would like to seek help if there is a possible way / code to capture a screenshot under Krypton platform that uses JAVA selenium. I'm having trouble in terms of it's standardization. Thanks!
var driver = new ChromeDriver()
driver.get("https://login.bws.birst.com/login.html/")
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE)
FileUtils.copyFile(scrFile, new File("c:\\tmp\\screenshot.png"))
As per the screenshots there seems to be some discrepency with the imports/Classes. Further to keep things simpler create destination folder within the Project Scope e.g. the Screenshots directory below:
To capture a screenshot using Java you can use the following solution:
Code Block:
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.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class takesScreenshot {
public static void main(String[] args) throws IOException {
System.setProperty("webdriver.chrome.driver", "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://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"));
}
}
Captured Image:
I tried the below code for taking full page screenshot. But only the visible area is captured,
public void Fullscreen (WebDriver driver)
{
try {
final Screenshot screenshot = new AShot().shootingStrategy(ShootingStrategies.viewportPasting(1000)).takeScreenshot(driver);
final BufferedImage image = screenshot.getImage();
ImageIO.write(image, "PNG", new File("D:\\" + "AShot_BBC_Entire.png"));
} catch(Exception e){
System.out.println(e.getMessage());
}
}
While working with Selenium Java Client v3.14.0, ChromeDriver v2.41, Chrome v 68.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
Want to add answer in case when you don't know what kind of screen is used. (retina or not)
In this case you need find devicePixelRatio of browser window:
Object output = ((JavascriptExecutor) webDriver).executeScript("return window.devicePixelRatio");
String value = String.valueOf(output);
float windowDPR = Float.parseFloat(value);
Then you can use ShootingStrategy with scaling;
ShootingStrategy shootingStrategy = ShootingStrategies.viewportPasting(ShootingStrategies.scaling(windowDPR), 100)
i hope you'll find a solution for my problem.
The page I try to test (I'll have an ARender deployed in my company and I need to test it) : http://arender.fr/ARender/
The xpath I use to click on next page (given by FireBug, I tried to use anothers but does the same thing):
//*[#id='id_#_0.7290579307692522']/tbody/tr/td[2]/div/img
I tried many things and I really don't find the solution, I already tried to make a Javascript executor click it...
Java code :
package firstPackage;
import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.NoSuchElementException;
import java.util.concurrent.TimeUnit;
import firstPackage.Props;
import firstPackage.methods;
import firstPackage.PropTech;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.junit.*;
import org.openqa.selenium.WebDriver;
import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;
import org.openqa.selenium.*;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.ie.InternetExplorerDriverLogLevel;
import org.openqa.selenium.ie.InternetExplorerDriverService;
import org.openqa.selenium.support.ui.Select;
public class TestSelenium {
private WebDriver driver;
protected static InternetExplorerDriverService service;
private StringBuffer verificationErrors = new StringBuffer();
#Before
public void setUp()
{
System.out.println("*******************");
System.out.println("launching IE browser");
System.setProperty("webdriver.ie.driver", PropTech.driverPath+"IEDriverServer.exe");
driver = new InternetExplorerDriver();
driver.manage().window().maximize();
}
#Test
public void test() throws Exception
{
driver.navigate().to("arender.fr" + "/ARender/");
Thread.sleep(15000);
driver.findElement(By.xpath("//div[#title='Next page']/img")).click();
}
#After
public void tearDown()
{
if(driver!=null)
{
System.out.println("Closing IE browser");
driver.quit();
//Kill les process
try {
Runtime.getRuntime().exec("taskkill /F /IM IEDriverServer.exe");
Runtime.getRuntime().exec("taskkill /F /IM iexplore.exe");
} catch (IOException e) {
e.printStackTrace();
}
}
}
It might be dinamically loaded on the page, try to use WebdriverWait. And please pay attention on xpath, I've changed it a little. Checked execution in IE
WebDriverWait wait = new WebDriverWait(driver, 30);
driver.get("http://arender.fr/ARender/");
//Click element after it bacomes clickable
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//td[div[#title='Next page']]"))).click();
The following XPath should work:
//div[#title='Next page']/img
Seems the ID which you used in you xpath is dynamically generated. (#id='id_#_0.7290579307692522') can you confirm it's remains same even after refreshing the page?
If not try to make xpath with some other attributes or use xpath whilecard search.
Xpath wildcard search
thanks
I need help with following combination,
OS: Windows 10
Browser used :Firefox 45.0.1
Java version:Java 8 update 51( 64 bit)
Selenium : library 2.47.1
Our code is simple.
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
import org.testng.annotations.Test;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.AfterClass;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.testng.Assert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
//import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class TestClass01
{
static final Logger logger1 = LogManager.getLogger(TestClass01.class.getName());
WebDriver driver ;
String baseUrl ;
static int testCount = 0 ;
String[] content_heading ;
List<WebElement> temp_list ;
WebDriverWait wait;
boolean exists;
#BeforeClass
public void beforeClass()
{
logger1.entry();
logger1.info("Entering the class : " + this.getClass().getSimpleName() );
driver = new FirefoxDriver();
baseUrl = "http://www.google.com";
logger1.info("Maximizing the browser window and setting up the implicit timeout for element/page loading....");
driver.manage().window().maximize();
//Specifies the amount of time the driver should wait when searching for an element
driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
logger1.info("Fetching the Homepage for Jacuzzi");
// launch Firefox and direct it to the Base URL
driver.get(baseUrl+"/");
}
}
However, it throws following error,
org.openqa.selenium.firefox.NotConnectedException: Unable to connect
to host 127.0.0.1 on port 7055 after 45000 ms. Firefox console output:
DEBUG Updating XPIState for
{"id":"{972ce4c6-7e08-4474-a285-3208198ce6fd}","syncGUID":"BbZlO30v46U7","location":"app-global","version":"45.0.1","type":"theme","internalName":"classic/1.0","updateURL":null,"updateKey":null,"optionsURL":null,"optionsType":null,"aboutURL":null,"icons":{"32":"icon.png","48":"icon.png"},"iconURL":null,"icon64URL":null,"defaultLocale":{"name":"Default","description":"The
default
theme.","creator":"Mozilla","homepageURL":null,"contributors":["Mozilla
Contributors"]},"visible":true,"active":true,"userDisabled":false,"appDisabled":false,"descriptor":"C:\Program
Files (x86)\Mozilla
Firefox\browser\extensions\{972ce4c6-7e08-4474-a285-3208198ce6fd}.xpi","installDate":1458533973089,"updateDate":1458533973089,"applyBackgroundUpdates":1,"skinnable":true,"size":22012,"sourceURI":null,"releaseNotesURI":null,"softDisabled":false,"foreignInstall":false,"hasBinaryComponents":false,"strictCompatibility":true,"locales":[],"targetApplications":[{"id":"{ec8030f7-c20a-464f-9b0e-13a3a9e97384}","minVersion":"45.0.1","maxVersion":"45.0.1"}],"targetPlatforms":[],"seen":true}
This was happening because of new issue in latest browser of firefox.
Update your selenium jars. The new version of firefox(Or different browser) is not supporting old jars of selenium.
Download both Selenium Server (formerly the Selenium RC Server) Selenium Client & WebDriver Language Bindings
Replace them with old jars you are using. Update your mozilla also so you can get the updated results
source :- http://docs.seleniumhq.org/download/
To overcome from this issue you also need to setPreference as xpinstall.signatures.required", false to firefox Profile and then pass it to driver object
firefoxProfile.setPreference("xpinstall.signatures.required", false);
Below code is working fine for me.
static WebDriver driver=null;
public static void main(String[] args) {
final FirefoxProfile firefoxProfile = new FirefoxProfile();
firefoxProfile.setPreference("xpinstall.signatures.required", false);
driver = new FirefoxDriver(firefoxProfile);
driver.get("https://www.google.de/");
Hope it will help you :)