How to use a already opened firefox for testing in Selenium - java

This declaration
WebDriver driver = new FirefoxDriver();
always opens a new instance window of Firefox. It doesn't use the already opened firefox.
Can anyone let me know how to use a already opened firefox for testing instead of opening a new one?

Use Remote Web Driver
like this .
System.Uri uri = new System.Uri("http://localhost:7055/hub");
WebDriver = new RemoteWebDriver(uri, DesiredCapabilities.Firefox());
it will use the already opened Firefox browser.
you can see the details of this approach in this blog post.
http://www.binaryclips.com/2016/03/selenium-web-driver-in-c-how-to.html

Be careful with that, because in case the driver crashes once, then all the test cases that have to be executed after that will be affected because they are using the same driver, also you will be sharing cookies, and perhaps sessions already opened previously, etc.
The more robust solution is to create a new WebDriver for each test cases because doing that you are making all your tests cases less dependent on the others.
If the reason that is motivating you is the time each WebDriver takes to be created, perhaps you could start thinking on run test cases in parallel for example with TestNG.
Thanks

Best way to do that is, extend RemoteWebDriver and override startSession method-:
Steps:
Start selenium server using command- java -jar selenium-server-standalone-3.x.x.jar. By default your session start on port 4444.
open url http://localhost:4444/wd/hub/static/resource/hub.html
start new firefox session clicking on create session button and select firefox browser.
Once the session start, copy the session id and paste it in property file or xml file where you want.
read session id form the file where you saved in following method
#Override
protected void startSession(Capabilities desiredCapabilities) {
String sid = getSessionIDFromPropertyFile();
if (sid != null) {
setSessionId(sid);
try {
getCurrentUrl();
} catch (WebDriverException e) {
// session is not valid
sid = null;
}
}
if (sid == null) {
super.startSession(desiredCapabilities);
saveSessionIdToSomeStorage(getSessionId().toString());
}
}

You should instantiate your webdriver only once, when making a test and then pass it as argument for the other classes in constructors. Something like this:
public class Test {
WebDriver driver = new FirefoxDriver();
#Test
public void testHomePage() {
HomePage hp = new HomePage(driver);
//code here }
}
public class HomePage{
private static WebDriver driver;
public HomePage(WebDriver driver) {
this.driver = driver;}
}

In Java, when you say new a new object is instantiated. For WebDriver, every new is a new browser window.
If you want the same browser to be used then use the same driver object.
driver.get("URL PATH");
This will go to the new Url with the already open browser.

Java example.
First, you need to have Selenium server running.
java -jar C:\selenium-server-standalone-2.53.0.jar
To start a new session (first script):
WebDriver driver = new RemoteWebDriver(
new URL("http://localhost:4444/wd/hub"),
DesiredCapabilities.firefox());
Then, to reuse (attach) that session (second script):
WebDriver driver = new RemoteWebDriver(
new URL("http://localhost:7055/hub"),
DesiredCapabilities.firefox());
Notice the different port number.

Related

Geckodriver / FirefoxDriver / Selenium - How to open (empty) start page or clear page?

I would like to clear a page after it has been loaded. Best way would be if the start page of the Firefox would be loaded, which is an empty page for me.
Background is, I'm getting some pages with the same framework but different data. Like you getting the history of a wikipedia article in a loop. Sometimes it seems to use the last, already gotten, page and not the new one. I don't know why this happens but it happens rarely from time to time. In this case an error would be great which I would get with a cleared page or different site.
A quick and dirty solution would be to load another page (like google or bing) but this causes additional data traffic and isn't really what I want.
In the only comment below is the line where I would like to navigate to the empty default page or clear the loaded page.
public class myGecko
{
WebDriver FireFoxDriver;
public void openFireFoxSingle()
{
try
{
System.setProperty("webdriver.gecko.driver","C:\\Gecko.exe");
File pathBinary = new File("F:\\Firefox.exe");
FirefoxBinary firefoxBinary = new FirefoxBinary(pathBinary);
firefoxBinary.addCommandLineOptions("--disable-extensions");
DesiredCapabilities desired = new DesiredCapabilities();
FirefoxOptions options = new FirefoxOptions();
desired.setCapability(FirefoxOptions.FIREFOX_OPTIONS, options.setBinary(firefoxBinary));
FireFoxDriver = new FirefoxDriver(options);
FireFoxDriver.manage().window().maximize();
}
catch(Exception e) {}
}
public void getPage(String myLink)
{
try
{
FireFoxDriver.get(myLink);
WebElement myDynamicElement = (new WebDriverWait(FireFoxDriver, 10)).until(ExpectedConditions.presenceOfElementLocated(By.id("col-content")));
Thread.sleep(2000L);
// HERE NOW NAVIGATE BACK TO START PAGE or an EMPTY PAGE or CLEAR THE PAGE
}
catch(Exception e) {return; }
}
}
How do I clear the page or/and navigate back to the empty default page?
What works for me but causes a page to load three times is:
FireFoxDriver.get(myLink);
FireFoxDriver.navigate().refresh();
FireFoxDriver.get(myLink);
With this I am completely sure, the page has been refreshed.
I use the latest Firefox 98.0, Selenium 4.12 and Geckodriver 0.3.0
But I had this issue also with older versions (Selenium 3.x and older Gecko).
The answer is to create FireFoxDriver.get("about:blank");

Click is happening some other place on Cart ICON in MSITE from appium code - Chrome browser

I am trying to click on cart icon on top right corner from Appium in chrome browser mobile.
Code to click :
driver.findElement(By.xpath("//a[#href='/viewcart']")).click();
URL : https://www.2gud.com/?cmpid=2G108229
Note: Please open this URL in mobile device and verify.
Error : Code is clicking somewhere else on mobile device.
This is working. Checked in Android 7.1 emulator
driver.findElement(By.xpath("//a[#href='/rv/viewcart']")).click();
public class Demo {
public static WebDriver driver = null;
public static void main(String args[]) throws InterruptedException {
System.out.println("Launching the chrome driver ");
System.setProperty("webdriver.chrome.driver","src\\test\\resources\\drivers\\chromedriver40.exe");
ChromeOptions options = new ChromeOptions();
options.setExperimentalOption("androidPackage", "com.android.chrome");
driver = new ChromeDriver(options);
driver.manage().timeouts().pageLoadTimeout(20,TimeUnit.SECONDS);
driver.get("https://www.2gud.com/?cmpid=2G108229");
Thread.sleep(3000);
driver.findElement(By.xpath("//a[#href='/rv/viewcart']")).click();
Thread.sleep(3000);
System.out.println(driver.getTitle());
driver.quit();
}
Try to click using mouse actions or JavaScript executor.
Try using the following code.
Xpath to find the view cart: //a[contains(#href,'viewcart')]
Executing a click via JavaScript has some behaviors of which you should be aware. If, for example, the code bound to the onclick event of your element invokes window.alert(), you may find your Selenium code hanging, depending on the implementation of the browser driver. That said, you can use the JavascriptExecutor class to do this. My solution differs from others proposed, however, in that you can still use the WebDriver methods for locating the elements.
// Assume driver is a valid WebDriver instance that has been properly instantiated elsewhere.
WebElement viewCart = driver.findElement(By.xpath("//a[contains(#href,'viewcart')]"));
JavascriptExecutor executor = (JavascriptExecutor)driver;
executor.executeScript("arguments[0].click();", viewCart);
You should also note that you might be better off using the click() method of the WebElement interface, but disabling native events before instantiating your driver. This would accomplish the same goal (with the same potential limitations), but not force you to write and maintain your own JavaScript.

How to know webDriver opened URL successfully

How to know WebDriver opened an URL successfully after driver.get(appURL)? I can see it opens nicely in a browser. But I would like to make sure programmatically.
Hey. Here I am asking whether driver.get(appURL) returns any response code like http response. Or I have to find a ID from the web page and find it, then make conclusion, but the approach seems too primitive. I am looking for more simple solution. Someone suggested assertTrue, but some reason Eclipse is giving long error.
The simplest way to do so, would be to assert over the page title of the url you have opened :
String actualTitle = driver.getTitle();
String expectedTitle = "YourExpectedPage"; // replace with the expected page title
org.junit.Assert.assertTrue(expectedTitle.equals(actualTitle));
you can wait some time and check expected result then check current url
String currentURL = null;
WebDriverWait wait = new WebDriverWait(driver, 10);
if(driver.findElement(By.xpath("//*[#id='someID']")).isDisplayed()){ //add id or xpath
currentURL = driver.getCurrentUrl();
System.out.println(currentURL);
}
Each browser has a default error page. For chrome i am using:
if(driver.findElement(By.xpath("//div[#class='error-code']")).isDisplayed()){
MessageBox.Show("chrome error page.");
}
Try this with simple statements
WebDriver driver=new FirefoxDriver();
driver.manage().window().maximize();
String baseUrl="https://stackoverflow.com/";
driver.get(baseUrl);
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
if(baseUrl.equals(driver.getCurrentUrl()))
{
System.out.println("URLS are matching");
}else
{
System.out.println("URLS are not matching");
}
As a End User we really don't have to be concerned about whether WebDriver instance opened an URL successfully or not because once the WebDriver instance requests for a URL, the Browser Client on opening the webpage/website (by default) returns document.readyState as complete to the WebDriver instance and only then our next line of code gets executed.
However, as an End User we can configure the WebDriver instance to act on different available states of the DOM as well. Currently Selenium recognizes document.readyState at 3 different stages as follows:
none - The document is still loading
eager - The document is interactive
normal - The document is complete
Hence our scripts can be written to configure the WebDriver instance to respond as per your requirement.

Switching between 2 windows in selenium webdriver with java

I am automating an application using selenium webdriver with java. In that i have to open a browser instance & perform some actions. After that i have to open another browser instance, perform some actions in it & close that instance. Then i have to return the control back to the first browser instance again to perform some other actions.
I tried using :
String winHandleBefore = driver.getWindowHandle();
//then open new instance and perfom the actions
driver.switchTo().window(winHandleBefore);
But this returned an error :
org.openqa.selenium.remote.SessionNotFoundException: no such session
How can i do this? Can anybody help?
When you did driver = new ChromeDriver(); you reinitialized the driver object, which caused the lost of the first window. You can see it by checking the number of window handles after opening the new window
WebDriver driver = new ChromeDriver();
int len = getWindowHandles().size(); // 1 as expected
driver = new ChromeDriver();
len = getWindowHandles().size(); // still 1, has only the new window
To solve this use temporary driver to open the new window
WebDriver tempDriver = new ChromeDriver();
// do some stuff
tempDriver.close();

Changing URL using WebDriver

I'm using Selenium WebDriver (Java) and am trying to change the URL after WebDriver has logged into a page.
Is there a way to either:
Change the URL of the current window, or
Open a new tab and go to another page.
Thanks!
You didn't share any code so i don't know how is your approach about it, I only share my knowledge about this subject.
1) For your first question i think you know how to open a new page with selenium web driver maybe you can use some wait method and then invoke the driver again.
//open browser
driver = new FirefoxDriver();
//login
driver.get("https://www.google.com/");
//set implicit wait
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
//Then invoke method again for your second request(I am not try this code maybe you need to create new driver object)
driver.get("https://www.stackoverflow.com");
2) For your second question this link help you.

Categories