Selenium: NoSuchElementException in Internet Explorer - java

I'm trying to port a Selenium script for an internal Webapp from Selenium IDE to a Selenium Grid setup with RemoteWebDrivers in Java.
The scripts work fine with Chrome and Firefox, but not in Internet Explorer. Every time I try to find an element in a page, I only get a NoSuchElementException (The page itself loads just fine).
Sample Code that exhibits the same behaviour using a Wikipedia page:
public class Wikipedia_test_IE {
private WebDriver driver = null;
private String baseUrl = null;
private boolean acceptNextAlert = true;
private StringBuffer verificationErrors = new StringBuffer();
#Before
public void setUp() throws Exception {
// DesiredCapabilities cap = DesiredCapabilities.firefox();
DesiredCapabilities cap = DesiredCapabilities.internetExplorer();
cap.setCapability(CapabilityType.VERSION, "9");
driver = new RemoteWebDriver (new URL("http://192.168.1.230:4444/wd/hub"), cap);
baseUrl = "https://en.wikipedia.org/wiki/Rosetta_%28spacecraft%29";
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
#Test
public void testAKTargobankTestfall1KN() throws Exception {
driver.get(baseUrl);
driver.findElement(By.linkText("space probe")).submit();
}
}
I've tried using findElement(By.Id) and findElement(By.cssSelector) - no effect. Putting in a delay between pageload and the selection has no effect either, nor does using click instead of submit.
I've enabled debug logging of the IE Driver, but the Output doesn't help me to understand what the problem may be - hope someone else can.
server.cc(239) Command: POST /session {"desiredCapabilities":{"platform":"WINDOWS","ensureCleanSession":true,"browserName":"internet explorer","version":"9"}}
IESession.cpp(43) Mutex acquired for session initalization
IESession.cpp(105) Releasing session initialization mutex
command.cc(33) Raw JSON command: { "command" : "newSession", "locator" : { }, "parameters" : {"desiredCapabilities":{"platform":"WINDOWS","ensureCleanSession":true,"browserName":"internet explorer","version":"9"}} }
BrowserFactory.cpp(68) Ignoring Protected Mode Settings: 0
BrowserFactory.cpp(71) Checking validity of Protected Mode settings.
BrowserFactory.cpp(984) Detected IE version: 9, detected Windows version: 6
BrowserFactory.cpp(1074) Found Protected Mode setting value of 0 for zone 1
BrowserFactory.cpp(1074) Found Protected Mode setting value of 0 for zone 2
BrowserFactory.cpp(1074) Found Protected Mode setting value of 0 for zone 3
BrowserFactory.cpp(1074) Found Protected Mode setting value of 0 for zone 4
BrowserFactory.cpp(74) Has Valid Protected Mode Settings: 1
BrowserFactory.cpp(170) Starting IE using the IELaunchURL API
BrowserFactory.cpp(124) IE launched successfully with process ID 2188
BrowserFactory.cpp(130) Process with ID 2188 is executing iexplore.exe
BrowserFactory.cpp(313) Ignoring zoom setting: 0
BrowserFactory.cpp(581) Browser zoom level is 100%
IECommandExecutor.cpp(650) Persistent hovering set to: 1
ProxyManager.cpp(118) Using existing system proxy settings.
server.cc(308) Response: {"sessionId":"4aba017b-91e9-4f48-9f9f-f38b0464bb6b","status":303,"value":"/session/4aba017b-91e9-4f48-9f9f-f38b0464bb6b"}
server.cc(239) Command: GET /session/4aba017b-91e9-4f48-9f9f-f38b0464bb6b {}
command.cc(33) Raw JSON command: { "command" : "getSessionCapabilities", "locator" : { "sessionid" : "4aba017b-91e9-4f48-9f9f-f38b0464bb6b" }, "parameters" : {} }
IECommandExecutor.cpp(544) No alert handle is found
server.cc(308) Response: {"sessionId":"4aba017b-91e9-4f48-9f9f-f38b0464bb6b","status":0,"value":{"browserAttachTimeout":0,"browserName":"internet explorer","cssSelectorsEnabled":true,"elementScrollBehavior":0,"enableElementCacheCleanup":true,"enablePersistentHover":true,"handlesAlerts":true,"ie.browserCommandLineSwitches":"","ie.ensureCleanSession":false,"ie.forceCreateProcessApi":false,"ie.usePerProcessProxy":false,"ignoreProtectedModeSettings":false,"ignoreZoomSetting":false,"initialBrowserUrl":"http://localhost:15278/","javascriptEnabled":true,"nativeEvents":true,"platform":"WINDOWS","requireWindowFocus":false,"takesScreenshot":true,"unexpectedAlertBehaviour":"dismiss","version":"9"}}
server.cc(239) Command: POST /session/4aba017b-91e9-4f48-9f9f-f38b0464bb6b/timeouts/implicit_wait {"ms":30000}
command.cc(33) Raw JSON command: { "command" : "implicitlyWait", "locator" : { "sessionid" : "4aba017b-91e9-4f48-9f9f-f38b0464bb6b" }, "parameters" : {"ms":30000} }
IECommandExecutor.cpp(544) No alert handle is found
server.cc(308) Response: {"sessionId":"4aba017b-91e9-4f48-9f9f-f38b0464bb6b","status":0,"value":null}
server.cc(239) Command: POST /session/4aba017b-91e9-4f48-9f9f-f38b0464bb6b/url {"url":"https://en.wikipedia.org/wiki/Rosetta_%28spacecraft%29"}
command.cc(33) Raw JSON command: { "command" : "get", "locator" : { "sessionid" : "4aba017b-91e9-4f48-9f9f-f38b0464bb6b" }, "parameters" : {"url":"https://en.wikipedia.org/wiki/Rosetta_%28spacecraft%29"} }
IECommandExecutor.cpp(544) No alert handle is found
Browser.cpp(421) Navigate Events Completed.
Browser.cpp(452) Browser ReadyState is not '4', indicating 'Complete'; it was 1
Browser.cpp(421) Navigate Events Completed.
Browser.cpp(437) Browser busy property is true.
(The last two lines repeat several times)
ElementRepository.cpp(107) Refreshing managed element cache. Found 0 to remove from cache.
Browser.cpp(421) Navigate Events Completed.
Browser.cpp(476) Waiting for document to complete...
Browser.cpp(481) Not in navigating state
server.cc(308) Response: {"sessionId":"4aba017b-91e9-4f48-9f9f-f38b0464bb6b","status":0,"value":null}
server.cc(239) Command: POST /session/4aba017b-91e9-4f48-9f9f-f38b0464bb6b/element {"using":"link text","value":"space probe"}
command.cc(33) Raw JSON command: { "command" : "findElement", "locator" : { "sessionid" : "4aba017b-91e9-4f48-9f9f-f38b0464bb6b" }, "parameters" : {"using":"link text","value":"space probe"} }
IECommandExecutor.cpp(544) No alert handle is found
ElementFinder.cpp(49) Using FindElement atom to locate element having linkText = space probe
Browser.cpp(114) No child frame focus. Focus is on top-level frame
Script.cpp(485) -2147024891 [Zugriff verweigert]: Unable to execute code, call to IHTMLWindow2::execScript failed
Script.cpp(171) Cannot create anonymous function
ElementFinder.cpp(84) Unexpected error attempting to find element by mechanism linkText with criteria space probe
Any ideas?

Thanks for the help. To answer some of the Questions noted above, which i should have included in the original Post:
-Yes, it's indeed IE 9
-I had already set protected mode to enabled in all security zones
-using click instead of submit did not make a difference (initially)
It just so happens that the VM that's running the Selenium node applied security updates during the night, and that included one for IE.
At first, i got a different error message than i did before - IE was not able to find the browser window that was just opened, and the windows were not closed either. All the security settings had been reset by the update.
After re-enabling protected mode everything now works. As Richard noted i did need to change the find element to .click() instead of .submit().
So, everything now works, and i have no idea why. Thanks again!

You should probably be using click(), not submit():
driver.findElement(By.linkText("space probe")).click();

I also had got also that error on tests that worked fine on FF but not on IE.
I can suggest you:
To check the protected mode settings on IE.
To disable native events on the IE driver.
To Use JavaScript on those particular cases (The worst one on my point of view).
This is a known problem with the IE driver.
http://jimevansmusic.blogspot.be/2012/08/youre-doing-it-wrong-protected-mode-and.html
http://jimevansmusic.blogspot.be/2013/01/revisiting-native-events-in-ie-driver.html

Try to use InternetExplorerDriver instead of RemoteWebDriver normally it shouldn't make a difference but with IE all is possible-.-
I got similar problems and I end up with the following Code which works for me:
#Before
public void setUp() {
//... some irrelevant Code ...
System.setProperty("webdriver.ie.driver", "Path to IEDriver.exe");
InternetExplorerDriver driver = new InternetExplorerDriver();
//... some irrelevant Code ...
}

You can write your code in the following way:
while(true) {
try {
driver.findElement(By.linkText("space probe")).submit();
break;
} catch (Exception e) {
continue;
}
}
I write my code like this so that the thread searches until success. When using implicitlyWait, the browser will only wait for the maximum of that time. But it may happen that your browser page loading has been completed but the desired portion is loaded by an ajax call. In that case your program will throw an error.

Related

Selenium not able to find new window handle in IE MODE but working in normal mode ( internet explorer )

I'm trying to switch to a new window that will open when I login to the previous page. After clicking the login button a new tab will be open and gets closed immediately then a new window is open, this window handle is not recognized by the Selenium IE driver in IE MODE but I'm able to switch to this new window while automating in normal Internet Explorer browser. Selenium version is 4.3.0.0.
The code that I'd tried to switch to that new windows:
Thread.sleep(3000); // This delay is to avoid the new tab that gets closed immediately without this delay the driver is trying to switch to that new tab, after that any operation leads to throwing no browser exception. So this line is saving from the issue.
String desiredTitle = "";
while (!desiredTitle.contains("new window")) {
for (String ewh: driver.getWindowHandles()) {
desiredTitle = driver.switchTo().window(ewh).getTitle();
}
}
There're known limitations in Selenium 4 for IE mode automation. One of the workarounds suggests waiting until the driver gets the handle. You can try the sample code provided in that doc.

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.

Getting error in Appium that mobile:longClick is not implemented..is there another way?

I'm automating a native Android app using Java and Appium version 1.2.0. I want to automate long press on a row in a list to bring up some options that are accessible through long press, right now I test it manually. This is what I have tried:
WebDriverWait wait = new WebDriverWait(driver, 30);
HashMap<String,String> longtapObj= new HashMap<String,String>();
WebElement elem = wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//android.widget.ListView[1]/android.widget.RelativeLayout[1]")));
JavascriptExecutor js = (JavascriptExecutor) driver;
longtapObj.put("element", ( (RemoteWebElement) elem).getId() );
js.executeScript("mobile:longClick", longtapObj);
Appium server log error:
2014-09-02T23:29:45.808Z - debug: Request received with params: {"args":[{"element":"5"}],"script":"mobile:longClick"}
2014-09-02T23:29:45.810Z - debug: Responding to client that a method is not implemented
2014-09-02T23:29:45.810Z - info: <-- POST /wd/hub/session/f66d9550-c47e-4380-a0f4-c819a12f59a9/execute 501 3.656 ms - 158
2014-09-02T23:29:48.518Z - info: --> GET /wd/hub/status {}
Eclipse JUnit error:
org.openqa.selenium.WebDriverException: Not yet implemented. Please help us: http://appium.io/get-involved.html (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 9 milliseconds
If a comment out the statement js.executeScript("mobile:longClick", longtapObj); no errors are thrown. Appreciate if anyone knows the right way to implement a log press using Appium in a native android app.
CHANGES IN VERSION 1.5
Remove long-deprecated mobile: xxx
So you should:
Install Android Support Repository...
The Android Testing Support library is available through the Android SDK Manager
To download the Android Support Repository through the SDK Manager:
Start the Android SDK Manager.
In the SDK Manager window, scroll to the end of the Packages list, find the Extras folder and, if necessary, expand to show its contents.
Select the Android Support Repository item.
Click the Install packages... button.
Use TouchAction
driver.performTouchAction(new TouchAction(driver).tap(x, y));
mobile:longClick is no longer supported by appium version greater than 1.0.0. As you are using Appium version 1.2.0. so you have to perform this action by using something like this.
Eg:
testObject = this.WaitAndGetElement();//element on which long tap is to be performed
TouchAction action = new TouchAction(rm);// rm is the instance of appium driver.
Thread.Sleep(1000);
action.Press(testObject).Wait(1000).Perform();
For more information you can visit: TouchAction
Please let me know if it helps
JavascriptExecutor js = (JavascriptExecutor) driver;
HashMap<String, String> longTapObject = new HashMap<String, String>();
longTapObject.put("element",((RemoteWebElement)w1).getId());
js.executeScript("mobile: longClick", longTapObject);
The above code is working for me in java
Appium version 1.2.4.1
public void longClick(String element) {
// TODO Auto-generated method stub
WebElement webElement = appiumDriver.findElement(By.xpath(element));
TouchAction Action = new TouchAction(appiumDriver);
Action.longPress(webElement).release().perform();
}

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