Recently, bump into this issues with selenium firefox driver.
Thanks in advance
Set UP
os.name: 'Mac OS X',
os.arch: 'x86_64',
os.version: '10.12.6',
java.version: '1.8.0_131'
Firefox version 56.0.1 (64-bit)
Gecko Driver Latest 0.19.0
The error shows failed:
org.openqa.selenium.SessionNotCreatedException: Tried to run command
without establishing a connection
I tried different ways to tackle it but always come with the same error.
1. update all the selenium test driver to the latest
2. specify the directory export PATH = $PATH driverDir
My code
package automationFramework;
import org.apache.commons.io.FileUtils;
import org.junit.*;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.safari.SafariDriver;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import static org.junit.Assert.assertEquals;
public class GeckoDriver {
private static WebDriver driver;
public static int random = 0;
private String baseURL;
// #BeforeClass : Executes only once for the Test-Class.
#BeforeClass
public static void setting_SystemProperties(){
System.out.println("System Properties seting Key value.");
}
// #Before : To execute once before ever Test.
#Before
public void test_Setup(){
System.out.println("Launching Browser");
if (random == 0) {
System.out.println("Start Chrome Browser Testing ");
System.setProperty("webdriver.gecko.driver", "/Users/Fannity/Desktop/Drivers/geckodriver"); // Chrome Driver Location.
driver = new FirefoxDriver();
}
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
System.out.println("Session ID : " + ((RemoteWebDriver) driver).getSessionId() );
}
#Test
public void selenium_ScreenShot() throws IOException {
baseURL = "https://www.google.com/";
driver.get(baseURL);
System.out.println("Selenium Screen shot.");
File screenshotFile = ((RemoteWebDriver) driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(screenshotFile, new File("/Users/Fannity/Desktop/JUNIT-Selenium.jpg"));
random += 1;
}
// #After : To execute once after ever Test.
#After
public void test_Cleaning(){
System.out.println("Closing Browser");
baseURL = null;
driver.close();
driver.quit();
}
// #AfterClass : Executes only once before Terminating the Test-Class.
#AfterClass
public static void clearing_SystemProperties(){
System.out.println("System Property Removing Key value.");
System.clearProperty("webdriver.gecko.driver");
}
}
ERROR
https://gist.github.com/Fenici/f82f885486de37ae110fda8d7430df6e
Your problem is here:
#After
public void test_Cleaning(){
System.out.println("Closing Browser");
baseURL = null;
driver.close();
driver.quit();
}
Try only with close().
Explanation here.
We generally get this , if we use driver.close() and driver.quit() together so it would be better if you remove driver.close();
public void test_Cleaning(){
System.out.println("Closing Browser");
baseURL = null;
driver.quit();
}
Related
breaking my head over the following piece of code in Java, trying to solve a recaptcha for my selenium tests at work before implementing them.
The use case I use: https://www.google.com/recaptcha/api2/demo
WebDriver driver = Selenium.getInstance();
Selenium.goToWebPage("https://www.google.com/recaptcha/api2/demo");
WebDriverWait wait = new WebDriverWait(driver, 5);
List<WebElement> allIFrames = SeleniumUtil.getWebElementNicelyByTagName(driver, wait, "iframe");
if(allIFrames == null){
return;
}
Optional<WebElement> captchaIFrame = allIFrames.stream().filter(webElement -> webElement.getAttribute("src").contains("recaptcha/api2/anchor")).findFirst();
if(!captchaIFrame.isPresent()){
return;
}
WebDriver frame = driver.switchTo().frame(captchaIFrame.get());
//System.out.println(frame.getPageSource());
WebElement recaptchaTokenElement = SeleniumUtil.getWebElementNicelyByXPath(frame, wait, "//*[#type='hidden']");
System.out.println(recaptchaTokenElement);
So with the system.outs i'm trying to find my way to the captcha token, but every time it returns a null element. What the SeleniumUtil so far does is mainly:
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(xpath)));
return driver.findElement(By.xpath(xpath));
And the same for By.CssSelector etc.
I am already in the right IFrame, because the page source is printen out correctly, but searching by #recaptcha-token (cssselector), recaptcha-token (id), //*#id="recaptcha-token" does not work.
Maybe someone can help me with this?
There is a iFrame where the driver needs to be switched to.
After few tries I've got:
standard chromedriver setup:
package selenium;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
public class WebDriverSetup {
public static String userDir = System.getProperty("user.dir");
public static String chromedriverPath = userDir + "\\resources\\chromedriver.exe";
public static WebDriver driver;
public static WebDriver startChromeDriver() {
System.setProperty("webdriver.chrome.driver", chromedriverPath);
ChromeOptions options = new ChromeOptions();
options.addArguments("--start-maximized");
driver = new ChromeDriver(options);
driver.manage().window().maximize();
return driver;
}
}
And getting the token:
package selenium;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
public class GoogleRecaptchaDemo extends WebDriverSetup {
public static void main(String[] args) {
WebDriver driver = startChromeDriver();
driver.get("https://www.google.com/recaptcha/api2/demo");
List<WebElement> frames = driver.findElements(By.tagName("iframe"));
driver.switchTo().frame(frames.get(0));
WebElement rc = driver.findElement(By.id("recaptcha-anchor-label"));
rc.click();
WebElement recaptchaToken = driver.findElement(By.id("recaptcha-token"));
String token = recaptchaToken.getAttribute("value");
System.out.println(token);
driver.quit();
}
}
My output, last line is the token:
Starting ChromeDriver 86.0.4240.22 (398b0743353ff36fb1b82468f63a3a93b4e2e89e-refs/branch-heads/4240#{#378}) on port 25872
Only local connections are allowed.
Please see https://chromedriver.chromium.org/security-considerations for suggestions on keeping ChromeDriver safe.
ChromeDriver was started successfully.
Pro 01, 2020 4:30:45 ODP. org.openqa.selenium.remote.ProtocolHandshake createSession
INFO: Detected dialect: W3C
03AGdBq24MumCzjDlQCrcb4N3BuIiHm6O7V5IKSNGP1wChYe9g1Vc1GR7_NsvKqKV1Jzb5yLUXCB-ko8satP3fgkXIZ1rbjz76FITaLRRZqRJteQdVzlyzYoUgsSWQ_xjCspDvKNl6uTRGP7EzhesblTBf7HyYmjDU26BZkji8NqMFypQUzUIWUE6CF1W_UeiGCwV4Cfr2UduHJPskDubiwT7jxhRrLKFF_nK8zruV9dStwynSGzrMjwtemZSZmj2ZVJPiTxiYIV2QRIPUYPQ7dXMezrqJDG2Vwn2M9AxHOacoFcBTDIiFYoENq11-jNDJT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Bx4DtlhqzNGvVbQmIOND
I am new to Appium and I was trying to execute a simple program which performs a click operation. But the click operation is not happening. Here is the code:
package com.android.touchactionss;
import java.net.MalformedURLException;
import java.net.URL;
import org.openqa.selenium.remote.DesiredCapabilities;
import io.appium.java_client.android.AndroidDriver;
public class Sample {
public static void main(String[] args) throws InterruptedException, MalformedURLException {
DesiredCapabilities cap = new DesiredCapabilities();
cap.setCapability("platformName", "Android");
cap.setCapability("deviceName", "xiaomi-2014818-204648717d62");
cap.setCapability("version", "5.1.1");
cap.setCapability("appActivity", "com.mediamushroom.copymydata.app.EasyMigrateActivity");
cap.setCapability("appPackage", "com.mediamushroom.copymydata");
AndroidDriver<?> driver = new AndroidDriver<>(new URL("http://127.0.0.1:4723/wd/hub"), cap);
Thread.sleep(5000);
try{
System.out.println("STARTED");
driver.findElementByAndroidUIAutomator(
"new UiSelector().resourceId(\"com.mediamushroom.copymydata:id/NextButton\")");
//driver.findElement(By.id("//*[#resource-id='com.mediamushroom.copymydata:id/NextButton']"));
System.out.println("ENDED");
}
catch(Exception exception){
exception.printStackTrace();
}
Thread.sleep(5000);
driver.quit();
}
}
No exception is thrown but the click operation didn't happen. I tried with both driver.findElement(By.id("")) and driver.findElementByAndroidUIAutomator() method. But none of them worked. I have attached the object properties screen.
Versions used: appium software version 1.6.2
appium java_client version 6.1.0
selenium 3.13
First, add the following import:
import io.appium.java_client.android.AndroidElement;
Next change your code:
AndroidDriver<?> driver = new AndroidDriver<>(new URL("http://127.0.0.1:4723/wd/hub"), cap);
to:
AndroidDriver<AndroidElement> driver = new AndroidDriver<AndroidElement>(new URL("http://127.0.0.1:4723/wd/hub"), cap);
You might need to change the URL to 0.0.0.0 but it depends on what your Appium Server settings are. They may be correct they way it is now.
Lastly, you need to use the following method to click the element:
driver.findElement(By.id("com.mediamushroom.copymydata:id/NextButton")).click();
Hi here is example in next few lines, try to use some testing framework, Junit, TestNg, I've removed main, used TestNG with this example:
Start Appium server:
Appium GUI (https://github.com/appium/appium-desktop/releases/tag/v1.6.2)
Appium via console : appium --address 127.0.0.1 --port 4723
when Appium server is up-an-running, call this code:
import io.appium.java_client.MobileElement;
import io.appium.java_client.android.AndroidDriver;
import org.openqa.selenium.By;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import java.net.MalformedURLException;
import java.net.URL;
public class TestAppium {
AndroidDriver<MobileElement> driver;
#BeforeTest
public void setup() {
DesiredCapabilities cap = new DesiredCapabilities();
cap.setCapability("platformName", "Android");
cap.setCapability("deviceName", "emulator-5554"); //used emulator, but should be set devices guid in Your case "xiaomi-2014818-204648717d62"
cap.setCapability("version", "5.1.1");
cap.setCapability("appActivity", "com com.mediamushroom.copymydata.app.EasyMigrateActivity");
cap.setCapability("appPackage", "com.mediamushroom.copymydata");
try {
driver = new AndroidDriver<>(new URL("http://127.0.0.1:4723/wd/hub"), cap);
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
#Test
public void testAppiumSimulator() {
MobileElement element = driver.findElement(By.id("NextButton"));
element.click();
// do some Assertion
Assert.assertTrue(//some condition//);
}
#AfterTest
public void tearDown() {
driver.quit();
}
}
And this is an simple Appium test...
Hope this helps,
Issue: I'm trying to close my webdriver and and used both driver.close and driver.quit in my code and no luck. Is it required to have the #Before parameter in order to use the #After?
Code:
import org.junit.After;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
public class Automate {
private WebDriver driver;
private String baseUrl;
private boolean acceptNextAlert = true;
private StringBuffer verificationErrors = new StringBuffer();
#Test
public void LaunchChrome_Method1() {`
System.setProperty("webdriver.chrome.driver","C:\\Users\\HASANK\\Desktop\\tEST\\chromedriver.exe");
ChromeOptions options = new ChromeOptions();
options.addArguments("disable-infobars");
WebDriver driver = new ChromeDriver(options);
driver.get("http://www.google.com");
driver.get("https://www.google.com/");
driver.findElement(By.id("lst-ib")).clear();
driver.findElement(By.id("lst-ib")).sendKeys("cnn");
driver.findElement(By.id("lst-ib")).sendKeys(Keys.ENTER);
driver.findElement(By.linkText("CNN - Breaking News, Latest News and Videos")).click();
}
#After
public void tearDown() throws Exception {
driver.close();
driver.quit();
}
Even i have faced the same issue earlier, try updating both the chrome and chromedriver and try one more time. If it is still not working try an alternate by creating a method
public static void killDriverInstance() {
try {
String basePath = System.getProperty("user.dir");
String finalPath = basePath + "\\src\\utils\\killDriver.bat";
Process process = Runtime.getRuntime().exec(finalPath);
process.waitFor();
} catch (Exception ex) {
System.out.println("Exception in killDriverInstance method:" + ex.toString());
}
}
and in killdriver.bat file write this
REM Kill Chrome Driver
taskkill /im chromedriver.exe /f
REM Kill Chrome browser
REM taskkill /im chrome.exe /f
Using this kind of method for this in C# language:
private void CloseChromeDriverProcesses()
{
var chromeDriverProcesses = Process.GetProcesses().
Where(pr => pr.ProcessName == "chromedriver");
if (chromeDriverProcesses.Count() == 0)
{
return;
}
foreach (var process in chromeDriverProcesses)
{
process.Kill();
}
}
I think that some minutes, and you can rewrite this, using Java language.
There is problem I cant resolve for 2 days. I need to login in many browsers in many machines on same sites. Its time-consuming task so I decide to do it with Selenium. I think problem is that while running test selenium does not save cookies. I find that its real to save cookies in file and then open them in next selenium tests but i need all browsers are logged in for manual testing. Here is my code
package automationFramework;
import java.io.File;
import java.util.concurrent.TimeUnit;
import org.junit.*;
import static org.junit.Assert.*;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
public class FirstTestCase {
private WebDriver driver;
private String baseUrl;
private boolean acceptNextAlert = true;
private StringBuffer verificationErrors = new StringBuffer();
#Before
public void setUp() throws Exception {
File profileDirectory = new File(
"C:\\Users\\User\\AppData\\Roaming\\Mozilla\\Firefox\\Profiles\\n8a2y7sp.default");//path to firefox profile
FirefoxProfile profile = new FirefoxProfile(profileDirectory);
driver = new FirefoxDriver(profile);
baseUrl = "http://facebook.com/";
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
#Test
public void testVk() throws Exception {
driver.get(baseUrl);
driver.findElement(By.id("email")).clear();
driver.findElement(By.id("email")).sendKeys(""); // login
driver.findElement(By.id("pass")).clear();
driver.findElement(By.id("pass")).sendKeys(""); //password
driver.findElement(By.id("loginbutton")).click();
}
#After
public void tearDown() throws Exception {
driver.quit();
String verificationErrorString = verificationErrors.toString();
if (!"".equals(verificationErrorString)) {
fail(verificationErrorString);
}
}
What exactly do you mean? Do you try to achieve multiple browsers that access the same site simultaneously? If so, you will need to set up more than one driver instance.
If you'd like to achieve it sequentially, just use a loop where you open the driver and get the URL, do your thing, then kill the driver instance, repeat.
The question above covers what I need I have created successful test scripts using eclipse on windows, but now i need to be able to run it in a linux vm through SSH and I have tried many things online and not had any success I know some changes may need to be done to the code also but I havnt managed to do that successfully either so please see the code below.
I have copied the src(test scripts) and libs(jars) files from the eclipse workspace to the linux vm and understood that to execute the selenium standalone server i use java -jar but that is about it. If you could walk me through the steps that need to be taken to run a test on firefox in the vm.
I have java and firefox installed.
Test Script
package test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
public class CorrectTestBackLink {
public BrowserList.DriverToUse used_driver = BrowserList.DriverToUse.IEXPLORER;
private BrowserSelector selectedDriver = new BrowserSelector(used_driver);
private WebDriver driver = selectedDriver.getDriver();
private StringBuffer verificationErrors = new StringBuffer();
private String baseUrl;
private static String resulterValue = "110";
private String valuecheck1;
#Before
public void setUp() throws Exception {
baseUrl = "http://url/";
//Set the column number and datatype of column by using either StringColumnNumber"Letter" or IntColumnNumber"Letter.
// Add aditional columns to database class where necessary.
}
public void calcResultChecker(){
driver.findElement(By.id("resulter")).getAttribute("value");
String valuecheck1 = driver.findElement(By.id("resulter")).getAttribute("value");
if (valuecheck1.equals(resulterValue)){
System.out.println("The Resulting value ("+valuecheck1+") is CORRRECT!");
}else{
System.err.println("The Resulting value is ("+valuecheck1+") is INCORRRECT!");
}
}
#Test
public void test2() throws Exception {
//calc page
driver.get(baseUrl + "calc.php");
assertEquals(baseUrl + "calc.php", driver.getCurrentUrl());
System.out.println("We are on the correct page ("+driver.getCurrentUrl()+").");
Thread.sleep(200);
System.out.println("Entering 10 into 'firstnumber' field!");
driver.findElement(By.name("firstnumber")).sendKeys("10");
Thread.sleep(200);
driver.findElement(By.name("secondnumber")).sendKeys("11");
System.out.println("Entering 11 into 'secondnumber' field!");
Thread.sleep(200);
System.out.println("Clicking calculate button!");
driver.findElement(By.name("Calculate")).click();
Thread.sleep(200);
//calc results page
assertEquals(baseUrl + "calcresult.php", driver.getCurrentUrl());
System.out.println("We are on the correct page ("+driver.getCurrentUrl()+").");
valuecheck1 = driver.findElement(By.id("resulter")).getAttribute("value");
assertEquals(valuecheck1, resulterValue);
Thread.sleep(200);
System.out.println("Clicking back Link!");
driver.findElement(By.linkText("Back")).click();
Thread.sleep(200);
//calc page check
assertEquals(baseUrl + "calc.php", driver.getCurrentUrl());
System.out.println("We are on the correct page ("+driver.getCurrentUrl()+").");
Thread.sleep(200);
System.out.println("Test Complete");
Thread.sleep(200);
driver.quit();
}
#After
public void tearDown() throws Exception {
driver.quit();
String verificationErrorString = verificationErrors.toString();
if (!"".equals(verificationErrorString)) {
fail(verificationErrorString);
}
}
}
Browser Selector
package test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
public class BrowserSelector {
private WebDriver driver;
public BrowserSelector(BrowserList.DriverToUse used_driver){
switch (used_driver){
case CHROME:{
System.setProperty("webdriver.chrome.driver", "C:/path/chromedriver.exe");
driver = new ChromeDriver();
break;
}
case FIREFOX:{
driver = new FirefoxDriver();
break;
}
case IEXPLORER:{
System.setProperty("webdriver.ie.driver","C:/path/IEDriverServer.exe");
DesiredCapabilities capabilities = DesiredCapabilities.internetExplorer();
capabilities.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, true);
driver = new InternetExplorerDriver(capabilities);
break;
}
}
}
public WebDriver getDriver(){
return driver;
}
}
People usually use either PhantomJS or "Headless Chrome" to run in a headless environment. Also, some people run regular browsers from a XVFB framebuffer. Here is a blog article that I found that explains how to install XVFB.
xvfb-run --server-args='-screen 0, 1024x768x16' google-chrome
-start-maximized http://example.com > /dev/null &
Using XVFB and VNC, you could probably login remotely and watch your tests run on the headless box but I haven't tried this. You would have to experiment with it.