nosuchwindowexception Selenium with PhantomJS Java - java

I am using headless PhantomJS browser to automate the application using phantomjs driver with selenium. (selenium java version 3.5.2 and phantomjs.exe)
I have a scenario where i will fill the form and submit it and then the browser gets closed and after closing the browser I am reusing the driver reference to get the URL. It works well when I am using the firefox driver with selenium 2.47.0.
Now I switched to the selenium phontamjsdriver and phantombrowser. Here when I make a call to the driver.get(url);after the browser gets closed it is throwing the nosuchwindowexception saying window is closed or inactive. But, the same code is working with the firefox driver
example:
driver.get(url);// first time works
submitForm(driver);//browser window gets closed.
driver.get(url);
The last line is throwing exception as:
nosuchwindowexception(selenium java with 3.5.2 version and phantomjs.exe).
But works well with the firefoxbrowser with selenium 2.4.7.

First of all, as you migrated from Selenium v2.47.0 to Selenium v3.5.2 it's worth to mention a lot have been changed with the availability of Selenium 3.x. Now Selenium-WebDriver is a W3C Recommendation Candidate and is compliant with WebDriver W3C Editor's Draft
NoSuchWindowException
NoSuchWindowException class extends NotFoundException and is majorly thrown while attempting:
WebDriver.switchTo().window(String windowName);
Now, a bit more details about your usecase, relevant HTML and your code block would have given us some more ideas what is going wrong. Perhaps the defination of submitForm(driver) holds the key to the solution of your question.
Best Practices
Here some of the best practices you can follow to avoid NoSuchWindowException:
Always strore the Parent Window Handle in a variable so that you can traverse back to the Parent Window as generally required.
Before invoking driver.switchTo().window(windowHandle); always induce WebDriverwait in-conjunction with ExpectedConditions method numberOfWindowsToBe(int).
Once you invoke driver.switchTo().window(windowHandle); induce WebDriverWait in-conjunction with ExpectedConditions method titleContains(java.lang.String title) to wait for the Page Loading to get completed to continue your Test Steps on the newly opened window.
To switch back to the parent window use the previously stored windowhandle.
Here is a sample code block to demonstrate Window/Tab handling:
package demo;
import java.util.Set;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class WINDOW_HANDLE_ITERATE_Firefox
{
public static void main(String[] args) throws Exception
{
System.setProperty("webdriver.gecko.driver", "C:\\Utility\\BrowserDrivers\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("http://www.google.com");
String parent_window = driver.getWindowHandle();
System.out.println("Parent Window Handle is: "+driver.getWindowHandle());
System.out.println("Page Title is: "+driver.getTitle());
((JavascriptExecutor) driver).executeScript("window.open('http://facebook.com/');");
new WebDriverWait(driver,10).until(ExpectedConditions.numberOfWindowsToBe(2));
Set<String> allWindows_1 = driver.getWindowHandles();
System.out.println("Total Windows: "+allWindows_1.size());
for(String hand1:allWindows_1)
if(!parent_window.equals(hand1))
{
driver.switchTo().window(hand1);
new WebDriverWait(driver,10).until(ExpectedConditions.titleContains("Facebook"));
String first_child_window = driver.getWindowHandle();
System.out.println("First Child Window Handle is: "+first_child_window);
System.out.println("First Child Window Page Title is: "+driver.getTitle());
driver.close();
}
driver.switchTo().window(parent_window);
System.out.println("Current Window Handle is : "+driver.getWindowHandle()+ " which is same as "+parent_window +", which is the parent window handle" );
driver.quit();
}
}
Console Output:
1531917836983 geckodriver INFO geckodriver 0.20.1
1531917836993 geckodriver INFO Listening on 127.0.0.1:9993
1531917837915 mozrunner::runner INFO Running command: "C:\\Program Files\\Mozilla Firefox\\firefox.exe" "-marionette" "-profile" "C:\\Users\\ATECHM~1\\AppData\\Local\\Temp\\rust_mozprofile.W5WqVulBNm9x"
1531917842220 Marionette INFO Listening on port 35364
1531917843126 Marionette WARN TLS certificate errors will be ignored for this session
Jul 18, 2018 6:14:03 PM org.openqa.selenium.remote.ProtocolHandshake createSession
INFO: Detected dialect: W3C
Parent Window Handle is: 4294967297
Page Title is: Google
Total Windows: 2
First Child Window Handle is: 4294967301
First Child Window Page Title is: Facebook – log in or sign up
Current Window Handle is : 4294967297 which is same as 4294967297, which is the parent window handle

This may be an issue to bring to the PhantomJS team here https://github.com/ariya/phantomjs/issues
Unfortunately screenshots in Selenium only capture the DOM and not address bar. If you're able to save the pagesource, you may be able to extract the URL. When viewing page source of this page I see tags which list various 3rd party apps, inside there is a content source which lists the URL.
<meta name="twitter:app:url:googleplay" content="http://stackoverflow.com/questions/51255939/nosuchwindowexception-selenium-with-phantomjs-java">
This may not be true for every site, but could be somewhere to look. You could also try and add this tag in yourself if you're the site owner.

Related

Selenium Java Client is not getting back the control once driver.get(URL) method is invoked

driver.get("MyURL");
System.out.println("URL is opened");
executeAutoItScript(scriptFileLocation);
when i open the URL i get an Authentication Required pop up.
To handle that I am using AutoIt script. But the problem is As soon as the first command
(driver.get("MyURL");)
is executed, Chrome will get open and the
Authentication pop up appears. And i have observed that the second line
System.out.println("URL is opened");
is not being executed. I debugged it and observed that the
control is not given to next line from
driver.get("MyURL");
and it hangs
there. I changed driver.get("MyURL"); to driver.navigate().to("MyURL"); but
there is no luck. Could anyone please help me to resolve this. Attached is
the pop up screenshot.
As per your code trials and the browser snapshot, it seems that the Browser Client (i.e. the Google Chrome Browser) is not returning back the control to the WebDriver instance and subsequently Selenium Java Client can't achieve the state of 'document.readyState' equal to "complete". Hence neither your next line of code:
System.out.println("URL is opened");
is getting executed, nor the AutoIt Script in next line:
executeAutoItScript(scriptFileLocation);
Solution
It is not clear from your question about the source of this Authentication Popup. Perhaps following the discussion Selenium - Basic Authentication via url you can pass the username and password being embedded within the URL as follows:
driver.get("http://admin:admin123#MyURL");
From: http://selenium-python.readthedocs.io/navigating.html
WebDriver will wait until the page has fully loaded (that is, the onload event has fired) before returning control to your test or script. It’s worth noting that if your page uses a lot of AJAX on load then WebDriver may not know when it has completely loaded. If you need to ensure such pages are fully loaded then you can use waits.
So, in this case your webpage is not fully loaded since it requires authentication. Here is what you can do
driver.get("MyURL");
executeAutoItScript(scriptFileLocation);
Thread.sleep(2000);// to wait for autoit script, you can also use other wait explicit wait
//Assert statement
System.out.println("URL is opened");
->First define the page load time for the driver.
->By using try-catch time out exception invoke the url.
->After that use robot class key events or key events class to enter the authentication details
Try the below one if any queries do lemme know:
driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS);
try{
driver.navigate().to("yourURL");
}
catch(TimeoutException te){
System.out.println(te);
System.out.println("Line went to Upto that Link");
after this you could proceed with the authentication pop-up code.
Do lemme know if you have any queries.
This helped me:
InternetExplorerOptions options = new InternetExplorerOptions();
options.setCapability("initialBrowserUrl", "about:blank");
options.setPageLoadStrategy(PageLoadStrategy.NONE);
WebDriver driver = new InternetExplorerDriver(options);
driver.manage().deleteAllCookies();
driver.manage().window().maximize();
driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS);
driver.get(url);
//execute AutoItScript goes here

selenium won't get URL?

this my code open fire fox and get google
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class auto {
public static void main(String[] args) {
System.setProperty("webdriver.gecko.driver", "//root//Desktop//jarselenium//geckodriver-v0.20.1-linux64/geckodriver");
WebDriver driver = new FirefoxDriver();
driver.manage().window().maximize();
//driver.get("https://www.easybooking.lk/login");
//driver.manage().timeouts().implicitlyWait(25, TimeUnit.SECONDS);
driver.get("https://www.google.com");
}
}
but when i run this code selenium open fire fox but wont get url im running this code in linux
As per the current implementation of Selenium v3.11.0, GeckoDriver 0.20.1 I don't see any major issue in your code block perhaps the trace logs would have helped us to understand your issue better. Having said that you need to follow the below mentioned steps :
As you are using Linux based System you need to pass the absolute path of the GeckoDriver within single forward slashes i.e. / as follows :
System.setProperty("webdriver.gecko.driver", "/root/Desktop/jarselenium/geckodriver-v0.20.1-linux64/geckodriver");
As GeckoDriver opens Firefox Browser client in maximized mode you need to omit the line of code :
driver.manage().window().maximize();

PhantomJS WebDriver headless: ".click" Method has no effect

I hope somebody can help me with my phantomJS problem.
I'm running version 1.9.8 on unix 64bit as a node that registers to a selenium hub running on jenkins. If I navigate to a HTML page with a link (which has no ID or name, which is why I'm addressing it via xpath - Unfortunately I cannot change the html code as it is external input), I'm trying to click it to navigate to the upcoming page. Using Firefox Driver this worked without any problems, and if I start a local selenium server (windows, phantomJS v. 1.9.8), it works aswell.
My code:
System.out.println("current url before click: " + getDriver().getCurrentUrl());
getDriver().findElement(By.xpath("//a")).click();
System.out.println("current url after click: " + getDriver().getCurrentUrl());
Output on local selenium (windows):
current url before click: https://initialpage.html
current url after click: https://www.my-link.com
Output on remote selenium grid (unix):
current url before click: https://initialpage.html
current url after click: https://initialpage.html
There is no error or similar, it just seems like the driver does stay on the old page. I already tried different phantomjs.cli.args while instantiating the WebDriver, adding several thread.sleep()'s and replacing click() by
getDriver().navigate().to(getDriver().findElement(By.xpath("//a")).getAttribute("href"));
but the output stays the same.
Just in case it matters, here is how I instantiate the webdriver:
driver = new RemoteWebDriver(new URL("http://servername:4444/wd/hub"), DesiredCapabilities.phantomjs());
I appreciate any help, thanks for the effort guys! If there are any questions left, feel free to ask! Thanks in advance!
So just in case somebody stumbles across this thread, I finally managed to figure it out after hours and hours of desperation. The problem was the instantiation of the webdriver which lacked an ssl related property. This is how it works for me now:
final ArrayList<String> cliArguments = new ArrayList<String>();
cliArguments.add("--ssl-protocol=any");
final DesiredCapabilities dCap = DesiredCapabilities.phantomjs();
dCap.setCapability(PhantomJSDriverService.PHANTOMJS_CLI_ARGS, cliArguments);
driver = new RemoteWebDriver(new URL("http://servername:4444/wd/hub"), dCap);

Unable to go for next Annotation of selenium browser automation with simple java codes

The thing what I wanted to do was automate the Firefox browser for search an item in the search bar. My java codes are as follows.
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class FlipkartTest {
public static void main(String[] args) {
CharSequence[] cs = {"Dell"};
//CharSequence[] d = String[]{"Dell"};
//String s = toString();
WebDriver driver = new FirefoxDriver();
driver.get("http://www.flipkart.com");
driver.findElement(By.id("fk-top-search-box")).sendKeys(cs);
driver.findElement(By.xpath("//input[#value=Search]")).click();
}
}
After debug or run the code a new Firefox window is appeared, But when click on next Annotation button, Nothing was happened. it doesn't go for next step such as opens the Flipcart.com site or searches the word.
After run the code, The console display a list. I found this line from it.
Caused by: org.openqa.selenium.firefox.NotConnectedException: Unable to connect to host 127.0.0.1 on port 7055 after 45000 ms.
So how I fix this problem?
As been answered here the problem is in mismatch between selenium and Firefox. Updating them to the latest version should solve the problem.
I recommend you to first set the properties of the Firefox driver and then create an instance of it. Something like this -
Webdriver driver=null;
System.setProperty("webdriver.firefox.driver"."//your firefox driver path");
driver=new FirefoxDriver();
Also try with ChromeDriver and InternetExplorerDriver and check if the problem still persists.

Selenium WebDriver IE11: JavaScript error

I am using WebDriver to help with regression testing of an Oracle Portal webapp, I have tried to get my test scripts functioning with IE11 but have not had any success.
I understand IEDriverServer.exe does not currently support WebDriver and the issue requires cooperation from Microsoft, I have tried the steps outlined in responses to Selenium issue #6511.
Protected mode settings are the same for all zones
Enhanced Protected Mode is disabled.
This is the code I am trying to execute:
#Test
public void Ts_Advertisement_disti() throws Exception {
launchURL(url);
LoginCheck("ts_Advertisement_disti");
// Check the Continue and Accept button for user
checkContinueAndAcceptButton();
// write out the title of the page in console
System.out.println(driver.getTitle());
assertEquals("Home", driver.getTitle());
assertTrue(isElementPresent(By.xpath("//div[contains(#class,'advertisement-holder')]")));
System.out.println("Element is present");
assertTrue(isElementPresent(By.xpath("//img[contains(#id,'ad_image')]")));
System.out.println("Element is present");
// Verify img <a> navigates to location
String follow_url = driver.findElement(By.xpath("//div[contains(#class,'advertisement-holder')]/a")).getAttribute("href");
System.out.println(follow_url);
Thread.sleep(5000);
// Follow advertisement and verify not on landing page
driver.get(follow_url);
assertNotEquals("Home", driver.getTitle());
driver.navigate().back();
Here is the output from TestNG:
org.openqa.selenium.ElementNotVisibleException: Received a JavaScript error attempting to click on the element using synthetic events. We are assuming this is because the element isn't displayed, but it may be due to other problems with executing JavaScript. (WARNING: The server did not provide any stacktrace information)
I would be grateful for any input on a resolution to this issue.
Thanks.

Categories

Resources