I am new to automation and trying to click on a dropdown in my application in Safari Browser but the script fails with error.
Please Help.
Error :
An unknown server-side error occurred while processing the command. (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 0 milliseconds
Build info: version: '3.141.59', revision: 'e82be7d358', time: '2018-11-14T08:17:03'
System info: host: 'DHRODCLPC0316', ip: '2409:4042:2098:9614:d857:22cd:8ec8:8ceb%en0', os.name: 'Mac OS X', os.arch: 'x86_64', os.version: '10.13.6', java.version: '13.0.2'
Driver info: org.openqa.selenium.safari.SafariDriver
Capabilities {applicationCacheEnabled: true, browserName: safari, cleanSession: true, cssSelectorsEnabled: true, databaseEnabled: true, handlesAlerts: true, javascriptEnabled: true, locationContextEnabled: false, nativeEvents: true, platform: MAC, platformName: MAC, rotatable: false, version: 13605.3.8, webStorageEnabled: true}
Session ID: C7B2C752-80D4-4453-B0C7-C35151B11F3C
Configuration :
Safari Version 13
Macbook Pro machine
Flow of Code
Open URL https://shop-lbs.mediatis.de
Login with credentials
Click on Quick order
Enter few codes to add in cart
Verify prices and checkout
Now select shipping address from dropdown
SCRIPT :
package lbs.leica;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.safari.SafariDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
public class Testcase_240_UAT_SAFARI extends ExtentReport_UAT
{
WebDriver driver;
public static String cardNumber = "4111-1111-1111-1111";
public static String Expiry = "01/29";
#BeforeTest
public void initialization()
{
test = extent.createTest("Order tests in UAT plethora of different order tests to verify tax, shipping, customer pricing, list pricing");
driver = new SafariDriver();
driver.manage().window().maximize();
driver.manage().deleteAllCookies();
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
driver.manage().timeouts().pageLoadTimeout(60, TimeUnit.SECONDS);
driver.manage().window().maximize();
driver.navigate().to("https://shop-lbs.mediatis.de");
System.out.println(driver.getTitle());
reportLog(driver.getTitle());
}
#Test
public void VerifyPrices() throws IOException, InterruptedException
{
driver.findElement(By.xpath("//*[#id='login-menu_login_title']")).click();
Thread.sleep(2000);
driver.findElement(By.xpath("(//*[#id='ShopLoginForm_Login'])[2]")).clear();
driver.findElement(By.xpath("(//*[#id='ShopLoginForm_Login'])[2]")).sendKeys("fjsim#buffalo.edu");
Thread.sleep(2000);
driver.findElement(By.xpath("(//*[#id='ShopLoginForm_Password'])[2]")).sendKeys("!InterShop00!");
reportLog("Entered username and password");
// Click on login in button
driver.findElement(By.xpath("(//*[#class='account-sign-in btn btn-primary'])[2]")).click();
Thread.sleep(5000);
reportLog("Clicked on Login ");
driver.findElement(By.xpath("//*[#class='view-account']")).click();
Thread.sleep(5000);
// Click on Quick Order
driver.findElement(By.xpath("//*[#class='quickorder-li hidden-xs']")).click();
Thread.sleep(5000);
reportLog("Clicked on Quick Order ");
// Click on Copy and paste
driver.findElement(By.xpath("(//*[text()='Copy and paste'])[1]")).click();
Thread.sleep(4000);
reportLog("Clicked on Copy and paste ");
//Enter Codes in text box
String[] voucherCodes = {"DS9800 1", "PA0515 2", "AR0222 3", "PA0027 4", "PA0571 5", "PA0813 6", "3801800 1", "3803650 1", "3800680 1", "3801815 1", "3800675 1", "3800080 1", "3800050CL 1", "3800161 1"};
WebElement input = driver.findElement(By.id("addToCartCopyAndPaste_textArea"));
for (String voucher : voucherCodes)
{
input.sendKeys(voucher+"\n");
}
reportLog("Entered Codes ");
//Click on Add to cart
driver.findElement(By.id("addToCartCopyAndPaste")).click();
Thread.sleep(9000);
reportLog("Clicked on Add to cart ");
//Verify and Print price
List<WebElement> VerifyPrice = driver.findElements(By.xpath("//*[#class=' col-xs-4 col-sm-offset-1 col-sm-2 list-item column-price single-price']"));
for(WebElement price:VerifyPrice)
{
System.out.println(price.getText());
reportLog(price.getText());
}
System.out.println();
//Verify and Print Product
List<WebElement> VerifyProduct = driver.findElements(By.xpath("//*[#class='product-title']"));
for(WebElement product:VerifyProduct)
{
System.out.println(product.getText());
reportLog(product.getText());
}
System.out.println();
Thread.sleep(4000);
//Click Checkout on shopping cart page
driver.findElement(By.xpath("//*[#class='btn btn-block btn-primary']")).click();
Thread.sleep(4000);
reportLog("Clicked Checkout on shopping cart page ");
//Select shipping address
JavascriptExecutor jse = (JavascriptExecutor) driver;
jse.executeScript("window.scrollTo(0, 200)");
Thread.sleep(5000);
WebDriverWait wait = new WebDriverWait(driver, 60);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("(//*[#class='btn dropdown-toggle btn-default'])[2]")));
System.out.println("Address dropdown visible");
WebElement e1 = driver.findElement(By.xpath("(//*[#class='btn dropdown-toggle btn-default'])[2]"));
e1.click();
Thread.sleep(5000);
System.out.println("Address dropdown Clicked");
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("(//*[#class='dropdown-menu inner'])[2]/li[1]")));
System.out.println(" dropdown visible");
driver.findElement(By.xpath("(//*[#class='dropdown-menu inner'])[2]/li[1]")).click();
Thread.sleep(2000);
System.out.println(" dropdown clicked");
reportLog("Selected first address ");
"An unknown server-side error occurred while processing the command."
This may indicate a bug in safaridriver. To more easily see what's going on, try passing 'safari:diagnose' capability to New Session. This will cause safaridriver to log protocol traffic to ~/Library/Logs/com.apple.WebDriver//. See man safaridriver for more information about enabling diagnostics.
If the protocol trace shows a command is failing unexpectedly (eg, HTTP 500), then please file an issue at https://feedbackassistant.apple.com/ so that it may be investigated by Apple. Including a reduced, standalone test case is super helpful for fixing issues, so please do that!
Thanks!
Related
Here is my code:
package working;
import java.util.List;
import java.util.concurrent.TimeUnit;
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.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class Test {
private static WebDriver driver;
public static void main(String[] args) throws Exception {
openBrowser();
System.out.println(scrape());
closeBrowser();
}
private static String table = "(//table[contains(#class,'datatable')])[1]";
private static String tr = table + "/tbody/tr";
private final static String next = table + "/preceding::a[text()='Next'][1]";
private final static String yesGotIt = "//body/div[contains(concat(\" \",normalize-space(#class),\" \"),\" gdpr-banner \")]/div/div[contains(concat(\" \",normalize-space(#class),\" \"),\" gdpr-button-wrapper \")]/button";
private static String scrape() throws Exception {
WebElement table_element = driver.findElement(By.xpath(table));
List<WebElement> tr_collection = table_element.findElements(By.xpath(tr));
int count = 1;
String rows = "";
driver.findElement(By.xpath(yesGotIt)).click();
while(count <= 3) {
for (WebElement trElement : tr_collection) {
List<WebElement> td_collection = trElement.findElements(By.xpath("td"));
for (WebElement tdElement : td_collection) {
rows += tdElement.getText() + "\t";
}
rows = rows + "\n";
}
System.out.println(rows);
WebDriverWait wait = new WebDriverWait(driver,30);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(next)));
driver.findElement(By.xpath(next)).click();
count += driver.findElements(By.xpath(next)).size();
System.out.println(count);
}
return rows;
}
private static void openBrowser() {
System.setProperty("webdriver.chrome.driver",
"E:\\eclipse-workspace\\src\\working\\selenium\\driver\\chromedriver.exe");
System.setProperty("webdriver.chrome.silentOutput", "true");
driver = new ChromeDriver();
driver.get("https://www.iata.org/en/publications/directories/code-search/");
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
}
private static void closeBrowser() {
driver.quit();
}
}
without while loop and next the code is working fine but when I run the aforementioned code its printing the first page table data 3 times repeatedly and throws the following error:
Mar 20, 2021 11:21:47 AM org.openqa.selenium.remote.ProtocolHandshake
createSession INFO: Detected dialect: OSS "Fly Armenia Airways"
Limited Liability Company Armenia VF 914 "NOVAIR" Limited Liability
Company Armenia NG 206 21 Air LLC UNITED STATES OF AMERICA 2I* 681
40-Mile Air, Ltd. UNITED STATES OF AMERICA Q5* 748 Air
Services Kenya H4* 874 874
2 "Fly Armenia Airways" Limited Liability Company Armenia VF 914
"NOVAIR" Limited Liability Company Armenia NG 206 21 Air LLC UNITED
STATES OF AMERICA 2I* 681 40-Mile Air, Ltd. UNITED STATES OF
AMERICA Q5* 748 Air Services Kenya H4* 874 874 "Fly Armenia
Airways" Limited Liability Company Armenia VF 914 "NOVAIR" Limited
Liability Company Armenia NG 206 21 Air LLC UNITED STATES OF
AMERICA 2I* 681 40-Mile Air, Ltd. UNITED STATES OF AMERICA Q5*
748 Air Services Kenya H4* 874 874
3 Exception in thread "main"
org.openqa.selenium.StaleElementReferenceException: stale element
reference: element is not attached to the page document (Session
info: chrome=89.0.4389.90) (Driver info: chromedriver=2.42.591088
(7b2b2dca23cca0862f674758c9a3933e685c27d5),platform=Windows NT
10.0.18363 x86_64) (WARNING: The server did not provide any stacktrace information) Command duration or timeout: 0 milliseconds For
documentation on this error, please visit:
https://www.seleniumhq.org/exceptions/stale_element_reference.html
Build info: version: '3.141.59', revision: 'e82be7d358', time:
'2018-11-14T08:25:53' System info: host: 'DESKTOP-832OS5B', ip:
'10.122.250.5', os.name: 'Windows 10', os.arch: 'amd64', os.version:
'10.0', java.version: '15.0.2' Driver info:
org.openqa.selenium.chrome.ChromeDriver Capabilities
{acceptInsecureCerts: false, acceptSslCerts: false,
applicationCacheEnabled: false, browserConnectionEnabled: false,
browserName: chrome, chrome: {chromedriverVersion: 2.42.591088
(7b2b2dca23cca0..., userDataDir: C:\Users\Windows\AppData\Lo...},
cssSelectorsEnabled: true, databaseEnabled: false, goog:chromeOptions:
{debuggerAddress: localhost:59261}, handlesAlerts: true,
hasTouchScreen: false, javascriptEnabled: true,
locationContextEnabled: true, mobileEmulationEnabled: false,
nativeEvents: true, networkConnectionEnabled: false, pageLoadStrategy:
normal, platform: XP, platformName: XP, rotatable: false,
setWindowRect: true, takesHeapSnapshot: true, takesScreenshot: true,
unexpectedAlertBehaviour: , unhandledPromptBehavior: , version:
89.0.4389.90, webStorageEnabled: true} Session ID: 5064d7cddc475396a421aa6d1639fb5c at
java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native
Method) at
java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:64)
at
java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at
java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:500)
at
java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:481)
at
org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:214)
at
org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:166)
at
org.openqa.selenium.remote.http.JsonHttpResponseCodec.reconstructValue(JsonHttpResponseCodec.java:40)
at
org.openqa.selenium.remote.http.AbstractHttpResponseCodec.decode(AbstractHttpResponseCodec.java:80)
at
org.openqa.selenium.remote.http.AbstractHttpResponseCodec.decode(AbstractHttpResponseCodec.java:44)
at
org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:158)
at
org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:83)
at
org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:552)
at
org.openqa.selenium.remote.RemoteWebElement.execute(RemoteWebElement.java:285)
at
org.openqa.selenium.remote.RemoteWebElement.getText(RemoteWebElement.java:166)
at working.Test.scrape(Test.java:41) at
working.Test.main(Test.java:21)
How can I print each page table data by clicking NEXT button?
Best regards
Refresh page after clicking Next button each time.
Declare table_element, tr_collection inside while.
Declare scrape() with void return and just call scrape() without print.
Also did some other changes in code.
import java.util.List;
import java.util.concurrent.TimeUnit;
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.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class Test
{
private static WebDriver driver;
public static void main(String[] args) throws Exception
{
openBrowser();
//System.out.println(scrape());
scrape();
closeBrowser();
}
private static String table = "(//table[contains(#class,'datatable')])[1]";
private static String tr = table + "/tbody/tr";
private final static String next = table + "/preceding::a[text()='Next'][1]";
private final static String yesGotIt = "//body/div[contains(concat(\" \",normalize-space(#class),\" \"),\" gdpr-banner \")]/div/div[contains(concat(\" \",normalize-space(#class),\" \"),\" gdpr-button-wrapper \")]/button";
private static void scrape() throws Exception
{
// WebElement table_element = driver.findElement(By.xpath(table));
// List<WebElement> tr_collection = table_element.findElements(By.xpath(tr));
int count = 1;
// String rows = "";
driver.findElement(By.xpath(yesGotIt)).click();
while (count <= 3) {
//Declare rows here - previous page's data will not repeatedly print
String rows = "";
System.out.println(count);
// Declare WebElement, List here
WebElement table_element = driver.findElement(By.xpath(table));
List<WebElement> tr_collection = table_element.findElements(By.xpath(tr));
for (WebElement trElement : tr_collection)
{
List<WebElement> td_collection = trElement.findElements(By.xpath("td"));
for (WebElement tdElement : td_collection)
{
rows += tdElement.getText() + "\t";
}
rows = rows + "\n";
}
System.out.println(rows);
WebDriverWait wait = new WebDriverWait(driver, 30);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(next)));
driver.findElement(By.xpath(next)).click();
count += driver.findElements(By.xpath(next)).size();
//System.out.println(count);
//refresh page to ignore StaleElementReferenceException
driver.navigate().refresh();
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(next)));
}
}
private static void openBrowser()
{
System.setProperty("webdriver.chrome.driver",
"E:\\eclipse-workspace\\src\\working\\selenium\\driver\\chromedriver.exe");
System.setProperty("webdriver.chrome.silentOutput", "true");
driver = new ChromeDriver();
driver.get("https://www.iata.org/en/publications/directories/code-search/");
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
}
private static void closeBrowser()
{
driver.quit();
}
}
Hope so everything is still working after changing table variable - look at console print. As visibility is focused on first table, last table's page change is not observeable. To focus on actual table's next button JavascriptExecutor is used and updated the whole code.
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class Test
{
private static WebDriver driver;
public static void main(String[] args) throws Exception
{
openBrowser();
//System.out.println(scrape());
scrape();
//closeBrowser();
}
//private static String table = "(//table[contains(#class,'datatable')])[1]";
private static String table = "(//table[contains(#class,'datatable')])[last()]";
private static String tr = table + "/tbody/tr";
private final static String next = table + "/preceding::a[text()='Next'][1]";
private final static String yesGotIt = "//body/div[contains(concat(\" \",normalize-space(#class),\" \"),\" gdpr-banner \")]/div/div[contains(concat(\" \",normalize-space(#class),\" \"),\" gdpr-button-wrapper \")]/button";
private static void scrape() throws Exception
{
// WebElement table_element = driver.findElement(By.xpath(table));
// List<WebElement> tr_collection = table_element.findElements(By.xpath(tr));
int count = 1;
// String rows = "";
driver.findElement(By.xpath(yesGotIt)).click();
while (count <= 3) {
//Declare rows here - previous page's data will not repeatedly print
String rows = "";
System.out.println(count);
// Declare WebElement, List here
WebElement table_element = driver.findElement(By.xpath(table));
List<WebElement> tr_collection = table_element.findElements(By.xpath(tr));
for (WebElement trElement : tr_collection)
{
List<WebElement> td_collection = trElement.findElements(By.xpath("td"));
for (WebElement tdElement : td_collection)
{
rows += tdElement.getText() + "\t";
}
rows = rows + "\n";
}
System.out.println(rows);
WebDriverWait wait = new WebDriverWait(driver, 30);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(next)));
//scroll to next button
JavascriptExecutor je = (JavascriptExecutor) driver;
WebElement we = driver.findElement(By.xpath(next));
je.executeScript("arguments[0].scrollIntoView(true);", we);
we.click();
driver.findElement(By.xpath(next)).click();
count += driver.findElements(By.xpath(next)).size();
//System.out.println(count);
//refresh page to ignore StaleElementReferenceException
driver.navigate().refresh();
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(next)));
}
}
private static void openBrowser()
{
System.setProperty("webdriver.chrome.driver",
"E:\\eclipse-workspace\\src\\working\\selenium\\driver\\chromedriver.exe");
System.setProperty("webdriver.chrome.silentOutput", "true");
driver = new ChromeDriver();
driver.get("https://www.iata.org/en/publications/directories/code-search/");
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
}
private static void closeBrowser()
{
driver.quit();
}
}
In My JavaCode , After clicking on Edit Description link a window get opens (i.e. Java Script Window) Images here 1st one gives anchor tag with attributes and 2nd one is opened window
Image 1::
Image 2:: Window image Along with Page Source here
What i need is A. Select the window open(java script) B. Enter the text into Text Area and click Ok.
control is waiting infinite # Select Window key word its not moving forward. I have to kill Control forcefully.
Here is the code
package Bala.AutoPratice.module1;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class WindowSwitch {
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
System.setProperty("webdriver.chrome.driver", "D:\\bin\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
//driver.manage().window().maximize();
driver.get("http://10.1.111.165/Login.aspx");
//To check if we have landed in the correct place
driver.findElement(By.id("LoginName")).sendKeys("User1");
driver.findElement(By.id("Password")).sendKeys("User1#123");
driver.findElement(By.id("LoginBtn")).click();
driver.get("http://10.1.111.165/roles.aspx");
driver.findElement(By.xpath("//*[#id=\"NewBtn\"]/span")).click();
driver.findElement(By.xpath("//*[#id=\"aspnetForm\"]/table/tbody/tr[1]/td[2]/a")).click();
String MainWindow=driver.getWindowHandle();
Set<String> s1=driver.getWindowHandles();
Iterator<String> i1=s1.iterator();
while(i1.hasNext())
{
String ChildWindow=i1.next();
if(!MainWindow.equalsIgnoreCase(ChildWindow))
{
// Switching to Child window
driver.switchTo().window(ChildWindow); // HERE IT NEVER SELECTS
driver.findElement(By.xpath("//*[#id=\"descript\"]")).sendKeys("gadddn#gmail.com");
driver.findElement(By.xpath("//*[#id=\"myform\"]/div/input[1]")).click();
// Closing the Child Window.
driver.close();
}
}
// Switching to Parent window i.e Main Window.
driver.switchTo().window(MainWindow);
driver.quit();
}
}
If i use this
Alert myAlert = new WebDriverWait(driver, 10).until(ExpectedConditions.alertIsPresent());
myAlert.sendKeys("I_am_bbk");
myAlert.accept();
I am getting this error
INFO: HTTP Status: '404' -> incorrect JSON status mapping for 'no such alert' (400 expected)
Exception in thread "main" org.openqa.selenium.TimeoutException: Expected condition failed: waiting for alert to be present (tried for 10 second(s) with 500 MILLISECONDS interval)
Build info: version: '3.4.0', revision: 'unknown', time: 'unknown'
System info: host: 'HIBAWL56712', ip: '10.158.126.17', os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '1.8.0_151'
Driver info: org.openqa.selenium.firefox.FirefoxDriver
Capabilities
It is pretty clear from your snapshot that the window which gets opened is a JavaScript window i.e. an Alert. To enter some text into the Text Area and click Ok you can use the following block of code :
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.openqa.selenium.support.ui.ExpectedConditions;
//other code
Alert myAlert = new WebDriverWait(driver, 10).until(ExpectedConditions.alertIsPresent());
myAlert.sendKeys("I_am_bbk");
myAlert.accept();
driver.quit();
I am trying to develop automation test on Amazon active Workspace, which uses Windows Server 2012 R2. I am doing it on local machine using localhost:8002. There is no internet access on the machine. So far I have following code:
package activeworkspaceprog;
import java.net.URL;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
public class ActiveWorkspaceProg {
WebDriver driver;
JavascriptExecutor jse;
public static void main(String[] args)
{
ActiveWorkspaceProg run = new ActiveWorkspaceProg();
run.invokeBrowser();
}
public void invokeBrowser()
{
try
{
System.setProperty("webdriver.ie.driver","C:\\Users\\Administrator\\Desktop\\IEDriverServer.exe");
DesiredCapabilities capability = DesiredCapabilities.internetExplorer();
driver = new RemoteWebDriver(
new URL("https://WIN-K0E8GV2L510:8002#hub-cloud.browserstack.com/wd/hub")
,capability);
capability.setCapability(InternetExplorerDriver.
INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, true);
driver = new InternetExplorerDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(50, TimeUnit.SECONDS);
driver.get("http://localhost:8002/awc/");
}
catch( Exception e)
{
e.printStackTrace();
}
}
}
I am using Selenium Standalone Server-3.13.0 jar and IEDriverServer.exe (version - 3.13.0.0) as my WebDriver.
But, I am just getting the following error,and I am stuck.
Error:
org.openqa.selenium.remote.UnreachableBrowserException: Could not
start a new session. Possible causes are invalid address of the remote
server or browser start-up failure. Build info: version: '3.13.0',
revision: '2f0d292', time: '2018-06-25T15:32:19.891Z' System info:
host: 'WIN-K0E8GV2L510', ip: '10.0.1.252', os.name: 'Windows Server
2012 R2', os.arch: 'amd64', os.version: '6.3', java.version:
'1.8.0_171'
Any help would be appreciated.
Just to give an update on my question. I was able to solve the issue by setting the security setting of the internet explorer to be at the same level. By default, the all zones security is set at different levels. The protected mode is enabled for Internet, Local intranet and Restricted sites. However, it is not enabled for Trusted sites. So, these different levels of security setting confuses the browser, which ends up throwing an error. So, make sure they are either enabled for all or disabled for all, so that they are set at the same level. Just following code should be enough to invoke the browser:
WebDriver driver;
JavascriptExecutor jse;
public static void main(String[] args)
{
ActiveWorkspaceProg run = new ActiveWorkspaceProg();
run.invokeBrowser();
}
public void invokeBrowser()
{
try
{
System.setProperty("webdriver.ie.driver","C:\\Users\\Administrator\\Desktop\\IEDriverServer.exe");
DesiredCapabilities capability = DesiredCapabilities.internetExplorer();
capability.setCapability("ignoreZoomSetting", true);
capability.setCapability(InternetExplorerDriver.
INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, true);
driver = new InternetExplorerDriver();
driver.manage().window().maximize();
driver.manage().deleteAllCookies();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.manage().timeouts().pageLoadTimeout(40, TimeUnit.SECONDS);
driver.get("http://localhost:8002/awc/");
}
catch( Exception e)
{
e.printStackTrace();
}
}
}
Look the following link for further understanding
Unable to launch IE browser in selenium webdriver
Selenium grid test case failed in headless browser mode only
Normal Browser Mode [Test Success]
selenium stand alone server : 3.0.1
Firefox : 38.0.1
ip : 192.168.1.40
Headless Browser Mode [Test Failed]
selenium stand alone server : 3.0.1
Firefox : 38.0
ip : 172.18.0.60
I run headless browser like below
xvfb-run java -Dwebdriver.firefox.marionette="/tmp/geckodriver" -Dwebdriver.firefox.bin="/tmp/firefox/firefox" -jar selenium-server-standalone-3.0.1.jar -role webdriver -hub http://192.168.1.106:4444/grid/register -port 5566 -host 172.18.0.60
Test Case Code:
package example;
import org.junit.Assert;
import org.openqa.selenium.*;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
import java.net.URL;
import java.util.concurrent.TimeUnit;
import java.net.MalformedURLException;
public class NewTest
{
public WebDriver driver;
public String URL, Node;
private JavascriptExecutor jse;
private String baseUrl;
protected ThreadLocal<RemoteWebDriver> threadDriver = null;
#Parameters({"browser","url"})
#BeforeTest
public void launchapp(String browser,String url) throws MalformedURLException
{
baseUrl = "http://myhost";
if (browser.equalsIgnoreCase("firefox"))
{
System.out.println(" Executing on FireFox");
String Node = url;
DesiredCapabilities cap = DesiredCapabilities.firefox();
cap.setBrowserName("firefox");
driver = new RemoteWebDriver(new URL(Node), cap);
// Puts an Implicit wait, Will wait for 10 seconds before throwing exception
driver.manage().timeouts().implicitlyWait(50, TimeUnit.SECONDS);
// Launch website
driver.navigate().to(baseUrl);
driver.manage().window().maximize();
}
else
{
throw new IllegalArgumentException("The Browser Type is Undefined");
}
jse = (JavascriptExecutor)driver;
}
#Test
public void functionalityTest() throws InterruptedException
{
driver.findElement(By.linkText("Sign In")).click();
driver.findElement(By.id("email")).clear();
driver.findElement(By.id("email")).sendKeys("xxxxx#xxx.xxx");
driver.findElement(By.id("pass")).clear();
driver.findElement(By.id("pass")).sendKeys("xxxxxx");
driver.findElement(By.id("send2")).click();
jse.executeScript("scroll(0, 250);");
driver.findElement(By.cssSelector(".customerlink a")).click();
Thread.sleep(1000);
driver.findElement(By.linkText("My Account")).click();
Thread.sleep(2000);
jse.executeScript("scroll(0, 250);");
Thread.sleep(1000);
jse.executeScript("scroll(0, -250);");
Thread.sleep(2000);
driver.findElement(By.cssSelector(".customerlink a")).click();
Thread.sleep(1000);
driver.findElement(By.linkText("Sign Out")).click();
Thread.sleep(2000);
}
#AfterTest
public void closeBrowser()
{
driver.quit();
}
}
I got exception in very first line of headless brwoser mode
07:16:53.571 INFO - Executing: [new session: Capabilities [{marionette=true, browserName=firefox, version=, platform=ANY}]])
07:16:53.580 INFO - Creating a new session for Capabilities [{marionette=true, browserName=firefox, version=, platform=ANY}]
07:17:00.268 INFO - Attempting bi-dialect session, assuming Postel's Law holds true on the remote end
07:17:02.648 INFO - Detected dialect: OSS
07:17:02.665 INFO - Done: [new session: Capabilities [{marionette=true, firefoxOptions=org.openqa.selenium.firefox.FirefoxOptions#3e74110c, browserName=firefox, moz:firefoxOptions=org.openqa.selenium.firefox.FirefoxOptions#3e74110c, version=, platform=ANY}]]
07:17:02.701 INFO - Executing: [implicit wait: 50000])
07:17:02.717 INFO - Done: [implicit wait: 50000]
07:17:02.724 INFO - Executing: [get: http://myhost])
07:18:03.564 INFO - Done: [get: http://myhost]
07:18:03.570 INFO - Executing: [maximise window])
07:18:03.580 INFO - Done: [maximise window]
07:18:03.593 INFO - Executing: [find element: By.linkText: Sign In])
07:18:53.917 WARN - Exception thrown
org.openqa.selenium.NoSuchElementException: Unable to locate element: {"method":"link text","selector":"Sign In"}
like
The error state clearly unable to locate element but how it worked in normal mode?
Is there any restriction in code to use headless browser mode?
Finally found, Headless browser does not take account of driver.manage().window().maximize(); so I set screen size through xvfb-run command
-s "-screen 0, 1920x1080x24"
Example:
xvfb-run -s "-screen 0, 1920x1080x24" java -Dwebdriver.firefox.marionette="/tmp/geckodriver" -Dwebdriver.firefox.bin="/tmp/firefox/firefox" -jar selenium-server-standalone-3.0.1.jar -role webdriver -hub http://192.168.1.106:4444/grid/register -port 5566 -host 172.18.0.60
Info: I'm using bootstrap so visible of element to be changed according to the screensize. So it will throw element not found exeception
I'm using Selenium Web Driver on Windows 7.
I'm trying to test a website that use authentication and I need to use SSL certificates.
When I use Firefox out of Selenium all works fine but I've noted that the Firefox browser session opened by Selenium doesn't have any certificates registered and so it's clear that it doesn't work.
Here you are the Advanced Preferences when I use Firefox "out" of Selenium
and here you are the same when I use the Firefox sessione opened by Selenium
I've tried to keep the session opened and to register manually the certificate but the browser session doesn't register the certificate.
Here you are my code if could be useful
package myTestProjects;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class GAMOPERA_Test_01 {
private static WebDriver driver = null;
public static void main(String[] args) throws InterruptedException {
// Create a new instance of the Firefox driver
System.out.println("Creo una nuova sessione del browser Firefox ...");
driver = new FirefoxDriver();
//Put a Implicit wait, this means that any search for elements on the page could take the time the implicit wait is set for before throwing exception
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
// It is always advisable to Maximize the window before performing DragNDrop action
System.out.println("Massimizzo la finestra del browser ...");
driver.manage().window().maximize();
Thread.sleep(3000L);
//Launch the Sistema Piemonte Home Page
System.out.println("Mi collego a Sistema Piemonte ...");
driver.get("http://<my_site_url>");
Thread.sleep(3000L);
// Find the element Accedi o
System.out.println("Accesso tramite certificato digitale ...");
driver.findElement(By.xpath("/html/body/div[6]/div/div/div[2]/form/table/tbody/tr[3]/td/input")).click();
//driver.findElement(By.className("loginbutton")).click();
Thread.sleep(3000L);
// Print TEST = OK!!
System.out.println("TEST = OK !!");
//driver.quit();
}
}
Any suggestions?
I've solved!
Surfing on the web I've found this post http://seleniummonk.blogspot.it/p/how-to-handle-ssl-cerificates.html that gave me the solution.
I need to use the "Firefox profile" (I use the default one ...), so I can have all the certificates I need to.
Here you're the new code that works
package myTestProjects;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.openqa.selenium.firefox.internal.ProfilesIni;
public class GAMOPERA_Test_01 {
private static WebDriver driver = null;
public static void main(String[] args) throws InterruptedException {
ProfilesIni profile = new ProfilesIni();
FirefoxProfile ffProfile = profile.getProfile("default");
// Create a new instance of the Firefox driver
System.out.println("Creo una nuova sessione del browser Firefox ...");
driver = new FirefoxDriver(ffProfile);
//Put a Implicit wait, this means that any search for elements on the page could take the time the implicit wait is set for before throwing exception
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
// It is always advisable to Maximize the window before performing DragNDrop action
System.out.println("Massimizzo la finestra del browser ...");
driver.manage().window().maximize();
Thread.sleep(3000L);
//Launch the Sistema Piemonte Home Page
System.out.println("Mi collego a Sistema Piemonte ...");
driver.get("<my_site_url>");
Thread.sleep(3000L);
// Find the element Accedi o
System.out.println("Accesso tramite certificato digitale ...");
driver.findElement(By.xpath("/html/body/div[6]/div/div/div[2]/form/table/tbody/tr[3]/td/input")).click();
//driver.findElement(By.className("loginbutton")).click();
Thread.sleep(3000L);
// Print TEST = OK!!
System.out.println("TEST = OK !!");
//driver.quit();
}
}
I hope this could be useful!
You can do that using Proxy. Through DesiredCapabilities you can configure the browser accordingly.
String PROXY = "localhost:8080";
org.openqa.selenium.Proxy proxy = new org.openqa.selenium.Proxy();
proxy.setHttpProxy(PROXY)
.setFtpProxy(PROXY)
.setSslProxy(PROXY);
DesiredCapabilities cap = new DesiredCapabilities();
cap.setCapability(CapabilityType.PROXY, proxy);
WebDriver driver = new InternetExplorerDriver(cap);
Code taken from SeleniumHQ
First create a profile as I created with "Test" in Firefox using below command in CMD:
"C:\Program Files\Mozilla Firefox\firefox.exe" -P
Then import your certificate in this newly created Firefox Profile with Password used to generate the certificate.
In my case this was a P12 extenstion Certificate.
Once done you can use below code in Selenium and Firefox will not popup for Certificate and you will be logged into the Portal or Website.
ProfilesIni allProfiles = new ProfilesIni();
FirefoxProfile myProfile = allProfiles.getProfile("Test");
myProfile.setPreference("security.default_personal_cert", "Select Automatically");
FirefoxOptions firefoxoptions = new FirefoxOptions();
firefoxoptions.setProfile(myProfile);
WebDriver driver = new FirefoxDriver(firefoxoptions);
Background I am using Firefox 56.0 and Windows 7