Error using gecko driver script for Selenium 3.11 - java

I am using Selenium version 3.11, gecko driver v0.20 and Firefox version 59. I used the system.setproperty script but I'm still getting this error:
Exception in thread "main" java.lang.IllegalStateException: The path to the driver executable must be set by the webdriver.gecko.driver system property
I also tried this with Firefox v40.
Please help me sort out this issue. Thanks.
The syntax i used is as follows :
System.setProperty("webdriver. gecko.driver","C:\geckodriver.exe");

Try to do something like that:
public void loadSystemProperties() {
try {
InputStream in = getClass().getResourceAsStream("/geckodriver");
File file = stream2file(in);
System.setProperty("webdriver.gecko.driver", file.getAbsolutePath());
LOGGER.info("Geckdriver found at {}", file.getAbsoluteFile());
} catch (IOException e) {
LOGGER.error(e.getMessage());
}
}
static File stream2file(InputStream in) throws IOException {
String PREFIX = "stream2file";
String SUFFIX = ".tmp";
final File tempFile = File.createTempFile(PREFIX, SUFFIX);
tempFile.deleteOnExit();
try (FileOutputStream out = new FileOutputStream(tempFile)) {
IOUtils.copy(in, out);
}
tempFile.setExecutable(true);
return tempFile;
}
I'm using commons-io, version 2.6. In addition, my geckodriver is in my resource folder.

Thanks for your response.My issue stands resolved after setting the geckodriver path in the environment variable settings.
But can anyone help me with one question: which latest firefox version will support firebug and xpath addons?

Related

Generate PDF with selenium chrome driver

To generate PDF from a HTML file, I want to use selenium Chrome driver.
I tried it with command line :
chrome.exe --headless --disable-gpu --print-to-pdf file:///C:invoiceTemplate2.html
and it works perfectly, So I wanted to do that with JAVA and here's my code :
System.setProperty("webdriver.chrome.driver", "C:/work/chromedriver.exe");
ChromeOptions options = new ChromeOptions();
options.addArguments("--headless", "--disable-gpu", "--print-to-pdf",
"file:///C:/invoiceTemplate2.html");
WebDriver driver = new ChromeDriver(options);
driver.quit();
The server is started with no problem, but chrome is opened with multiple tabs with the arguments I specified in Options.
Any solution to this ? thx.
This can indeed be done with Selenium and ChromeDriver (tested with Chrome version 85), but using the "print-to-pdf" option when starting Chrome from the webdriver is not the solution.
The thing to do is to use the command execution functionality of ChromeDriver:
https://www.selenium.dev/selenium/docs/api/java/org/openqa/selenium/remote/RemoteWebDriver.html#execute-java.lang.String-java.util.Map-
There is a command called Page.printToPDF that provides PDF output functionality. A dictionary containing the item "data", with the resulting PDF in base-64-encoded format, is returned.
Unfortunately, I do not have a full Java example, but in this answer, there is a C# example (Selenium methods are named differently in C# compared to Java, but the principle should be the same):
https://stackoverflow.com/a/63970792/2416627
The Page.printToPDF command in Chrome is documented here:
https://chromedevtools.github.io/devtools-protocol/tot/Page/#method-printToPDF
UPDATE:
we noticed that the original workaround was not always working properly, and we went for a Selenium + ChromeDriver:
public void generatePdf(Path inputPath, Path outputPath) throws Exception
{
try
{
ChromeOptions options = new ChromeOptions();
options.addArguments("--headless", "--disable-gpu", "--run-all-compositor-stages-before-draw");
ChromeDriver chromeDriver = new ChromeDriver(options);
chromeDriver.get(inputPath.toString());
Map<String, Object> params = new HashMap();
String command = "Page.printToPDF";
Map<String, Object> output = chromeDriver.executeCdpCommand(command, params);
try
{
FileOutputStream fileOutputStream = new FileOutputStream(outputPath.toString());
byte[] byteArray = java.util.Base64.getDecoder().decode((String) output.get("data"));
fileOutputStream.write(byteArray);
fileOutputStream.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
catch (Exception e)
{
e.printStackTrace(System.err);
throw e;
}
}
If this will be called frequently I suggest reusing the driver object because it takes a while to initialize.
Remember to close or quit the driver to avoid leaving Zombie chrome processes behind and also remember to install ChromeDriver in your machine.
Original Solution:
Not being able to get the desired outcome using ChromeDriver my workaround was to call the headless chrome in the command-line from my Java program.
This is working on Windows but just changing the contents of the paths used in the command variable should make it work in Linux too.
public void generatePdf(Path inputPath, Path outputPath) throws Exception {
try {
String chromePath = "C:/Program Files (x86)/Google/Chrome/Application/chrome.exe";
String command = chromePath + " --headless --disable-gpu --run-all-compositor-stages-before-draw --print-to-pdf=" + outputPath.toString() + " " + inputPath.toString();
// Runs "chrome" Windows command
Process process = Runtime.getRuntime().exec(command);
process.waitFor(); // Waits for the command's execution to finish
}catch (Exception e){
e.printStackTrace(System.err);
throw e;
}finally{
// Deletes files on exit
input.toFile().deleteOnExit();
output.toFile().deleteOnExit();
}
}
Note: both input and output paths are temporary files created with NIO.
The code will help you save the page in PDF format on Selenium c#
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
protected void PDFconversion(ChromeDriver driver, string root, string rootTemp)
{
//Grid.Rows.Add(TxtBxName.Text, TxtBxAddress.Text);
try
{
IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
Thread.Sleep(500);
js.ExecuteScript("setTimeout(function() { window.print(); }, 0);");
Thread.Sleep(500);
driver.SwitchTo().Window(driver.WindowHandles.Last());
Thread.Sleep(500);
string JSPath = "document.querySelector('body>print-preview-app').shadowRoot.querySelector('#sidebar').shadowRoot.querySelector('#destinationSettings').shadowRoot.querySelector('#destinationSelect').shadowRoot.querySelector('print-preview-settings-section:nth-child(9)>div>select>option:nth-child(3)')";
Thread.Sleep(500);
IWebElement PrintBtn = (IWebElement)js.ExecuteScript($"return {JSPath}");
Thread.Sleep(500);
PrintBtn.Click();
string JSPath1 = "document.querySelector('body>print-preview-app').shadowRoot.querySelector('#sidebar').shadowRoot.querySelector('print-preview-button-strip').shadowRoot.querySelector('cr-button.action-button')";
Thread.Sleep(1000);
IWebElement PrintBtn1 = (IWebElement)js.ExecuteScript($"return {JSPath1}");
PrintBtn1.Click();
Thread.Sleep(1000);
SendKeys.Send("{HOME}");
SendKeys.Send(rootTemp + "\\" + "result.pdf"); // Path
SendKeys.Send("{TAB}");
SendKeys.Send("{TAB}");
SendKeys.Send("{TAB}");
SendKeys.Send("{ENTER}");
Thread.Sleep(1000);
}
catch (Exception ex){}
}
You have to do two things.
First: Make a screenshot using selenium.
Second: Convert that screenshot using any pdf tool, like itext. Here I am showing a complete example of how to do this.
Step 1: Download the jar of itext from here and add the jar file to your build path.
Step 2: Add this code to your project.
ChromeOptions options = new ChromeOptions();
options.addArguments("disable-infobars");
options.addArguments("--print-to-pdf");
WebDriver driver = new ChromeDriver(options);
driver.get("file:///C:/invoiceTemplate2.html");
try {
File screenshot = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(screenshot, new File("screenshot.png"));
Document document = new Document(PageSize.A4, 20, 20, 20, 20);
PdfWriter.getInstance(document, new FileOutputStream("webaspdf.pdf"));
document.open();
Image image = Image.getInstance("screenshot.png");
document.add(image);
document.close();
}
catch (Exception e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
Note: To use the mentioned itext package, add the required imports to your code.
import com.itextpdf.text.Document;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.pdf.PdfWriter;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;

The driver executable does not exist: D:\Firefox\geckodriver.exe

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class sasas {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.setProperty("webdriver.gecko.driver","D:\\Firefox\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
String appUrl = "https://accounts.google.com";
driver.manage().window().maximize();
driver.get(appUrl);
System.out.println("Test script executed successfully.");
driver.close();
}
}
this is the sample code i am trying. when i run i get the error message as "The driver executable does not exist: D:\Firefox\geckodriver.exe" please help me to proceed. i added the location in environmental variable then too i get this error . PATH i added as D:\Samplecode.
kindly help me
(1) To use gecko driver, make sure you are using Firefox version 55 and above to get better gecko Web-Driver feature support, find out more here
(2) Perhaps, you should downgrade Selenium to a lower version i.e. version 2.53.1. Selenium version 2.53.1 runs perfectly on Firefox 47.0.1 and lower, does not require using web driver API. I have ran your code against this and it worked fine.
public class Sasas {
public static void main(String[] args) {
WebDriver driver = new FirefoxDriver();
String appUrl = "https://accounts.google.com";
driver.manage().window().maximize();
driver.get(appUrl);
System.out.println("Test script executed successfully.");
driver.close();
}
}
Use the relative path:
JAVA
1.- In your project, create the Drivers/Win/Firefox/geckodriver.exe folder and add your .exe
2.- Replace:
System.setProperty("webdriver.gecko.driver","D:\\Firefox\\geckodriver.exe");
For:
String path = System.getProperty("user.dir") + "/Drivers/Win/Firefox/Geckodriver.exe";
System.setProperty("webdriver.gecko.driver", path);
Note: using the relative path is the most optimal

File not reading in selenium - maven framewaork

I tried to create a quick framework. in that I created below-mentioned classes:
Config file(All browsers path)
configDataProvider java class(reads the above file)
BrowserFactory class(has firefox browser object)
configDataProviderTest class(access data from dconfigDataProvider class)
now its not reading the paths mentioned in config.properties file.
I have provided all correct path and attached screenshots:
Looks like a problem is at your ConfigDataProvider class.
Firstly, you using Maven for building your project. Maven has defined project structure for code sources and for resources:
/src/main/java
/src/main/resorces
Thus, much better to put your .properties file there.
Second, you don't need to set the full path to your config file.
Relative path will be just enough. Something like below:
public class PropertiesFileHandler {
private static Logger log = Logger.getLogger(PropertiesFileHandler.class);
public static final String CONFIG_PROPERTIES = "src/main/resources/config.properties";
public static final String KEY = "browser.type";
public static BrowserType readBrowserType() {
BrowserType browserType = null;
Properties properties = new Properties();
try (InputStream inputStream = new BufferedInputStream(new FileInputStream(CONFIG_PROPERTIES))) {
properties.load(inputStream);
browserType = Enum.valueOf(BrowserType.class, properties.getProperty(KEY));
} catch (FileNotFoundException e) {
log.error("Properties file wasn't found - " + e);
} catch (IOException e) {
log.error("Problem with reading properties file - " + e);
}
return browserType;
}
}
Lastly, if you are building framework you don't need to put everything under src/main/test. This path specifies tests with future possibilities to be executed with maven default lifecycle - mvn test.
The core of your framework can look like:
Two things which I noticed:
Don't give path in your properties path within ""
all the path seperators should be replaced with double backward slash \\ or single forward slash /

Java JDBC-ODBC cannot load driver for Excel

import java.sql.Connection;
import java.sql.DriverManager;
public class ConnectionExample {
public static void main(String args[]) {
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
} catch (Exception e) {
System.out.println("JDBC-ODBC driver failed to load.");
return;
}
try {
Connection con = DriverManager.getConnection("jdbc:odbc:abcdefg", "", "");
con.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
This code always prints
"JDBC-ODBC driver failed to load."
I can't understand what the problem is.. I follow these steps:
go to c:\windows\sysWOW64\odbcad32.exe
system dsn tab - add -> Microsoft Excel Driver (*xls, *xlsx, *xlsm, *xlsb)
give Data Source Name abcdefg
Select Workbook -> go to myFile excel path and add it -> OK
and then run my code... where is the mistake?
The JDBC-ODBC Bridge is obsolete and has been removed from Java 8. If you need to manipulate an Excel document and you are unable (or unwilling) to downgrade your environment to Java 7 then you might want to investigate Apache POI.

Uploading file using selenium javascript error

I have browse button to browse for the file. After browsing there is a import button which will actually import the file.
I'm able to browse the path using the following code:
public static void uploadFiles(String object, String data) {
try {
String filemode="";
Capabilities cap = ((RemoteWebDriver) driver).getCapabilities();
String browsername = cap.getBrowserName();
//System.out.println(browsername);
if (browsername.contains("chrome")){
filemode= "Open";
}
else if (browsername.contains("firefox")){
filemode= "File Upload";
}
else if (browsername.contains("explorer")){
filemode = "Choose File to Upload";
}
String EXE_FILE=DriverScript.EXE_FILENAME;
String[] command={EXE_FILE,filemode,data};
Runtime.getRuntime().exec(command);
Thread.sleep(5000);
} catch (Exception e) {
}
}
But when I click on the import button after that "JavaScript error (WARNING: The server did not provide any stacktrace information)" exception is thrown. EXE_FILE is the path to Fileload.exe which is used for browsing
Uploading a file using Selenium:
WebElement upload = driver.findElement(By.id("identifier of input tag"));
upload.sendKeys("path to file");
Remove capability INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS if you're using it in your test code and manually set your IE protected mode settings to be the same for all zones.
It should fix the problem.

Categories