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

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);

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

nosuchwindowexception Selenium with PhantomJS 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.

TypeError: Cannot find function createHTMLDocument in object

Selenium WebDriver (Java) gives the following error when running tests using a headless browser (either Firefox or Chrome) however, it runs without a problem when using a visible browser (e.g. Firefox).
org.openqa.selenium.WebDriverException: com.gargoylesoftware.htmlunit.ScriptException: TypeError: Cannot find function createHTMLDocument in object [object DOMImplementation]. (http://code.jquery.com/jquery-2.2.0.min.js#4)
There doesn't seem to be anything in the documentation about an error like this and trawling through SO hasn't turned up anything.
I'm new to Selenium WebDriver so I'm hoping it's just something obvious I've missed.
//If intialised like this it fails with the above error
webDriver = new HtmlUnitDriver(BrowserVersion.FIREFOX_38, true);
webDriver = new HtmlUnitDriver(BrowserVersion.CHROME);
//If initialised like this, it works
webDriver = new FirefoxDriver();
This is because your version of HtmlUnit misses an implementation of DOMImplementation.createHTMLDocument(). Please try with the latest version or even better with the latest snapshot.

Selenium 2 WebDriver UnhandledAlertException Java

Now before I start getting scolded, I DID read through most of the existing questions about this and applied different solutions (which mostly repeat the same thing), but it still does not work for me.
I have a maven project with all necessary dependencies, and the website in testing is done specifically for IE and requires me to have a specific certificate in order to access it. I have the certificate for it, and when I go onto the website, before it loads the page it asks me to confirm that I have the certificate and I need to confirm on the pop-up window, THEN the login page fully loads.
I have done to typical:
WebDriverWait wait = new WebDriverWait(driver, 3);
try {
// Handle alert box
driver.navigate().to("https://ke.m-pesa.com/ke/");
wait.until(ExpectedConditions.alertIsPresent());
Alert alert = driver.switchTo().alert();
alert.accept();
}
catch(Exception e) {
//whatever
}
Can you tell me where I am going wrong? So far I have used only Selenium RC up till now so this webdriver stuff is still kind of new to me. Please tell me if you need any more info I need to provide.
Why do I still get the UnhandledAlertException?? and why can't I access the login page until I manually press the OK button?
Did you try using Robot? Something like :
Alert alert = driver.switchTo().alert();
Robot a = new Robot();
a.keyPress(KeyEvent.VK_ENTER);
Why robot and not Actions
From this answer :
There is a huge difference in terms of how do these tools work.
Selenium uses the WebDriver API and sends commands to a browser to
perform actions (through the "JSON wire protocol").
Java AWT Robot uses native system events to control the mouse and
keyboard.
If you are doing browser automation, ideally, you don't ever use
things like Robot since usually the functionality provided by selenium
is more than enough. Though, there are cases when there is a browser
or native OS popup opened, for example, to upload/download a file -
this is something that can be also solved with Robot -

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