Selenium cannot find element - google-chrome

Having some issues using Selenium web driver in Chrome.
My goal is to give the user ~15-30 seconds to log in on there own and then start doing automated testing.
The problem is after I click the login button and go to the next page, I am not able to find elements by xpath, id, etc.
public static void runTest() throws InterruptedException {
System.setProperty("webdriver.chrome.driver", System.getProperty("user.dir")+"/chromedriver");
WebDriver driver = new ChromeDriver();
driver.get("http://www.url.com");
driver.manage().window().maximize();
Thread.sleep(15000);
driver.findElement(By.xpath("//*[#id=\"content-main\"]/div/div/form/div/p/input")).click();
System.out.println("User has logged in and it has found element for Attachment Upload.");
Thread.sleep(15000);
driver.findElement(By.xpath("//*[#id=\"invoiceMenu\"]/a")).click();
}
I have also tried using explicit waits and have had no luck for example:
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement element = wait.until(
ExpectedConditions.visibilityOfElementLocated(By.id("someid")));
The error I am usually getting back is:
Exception in thread "main" org.openqa.selenium.TimeoutException: Expected condition failed: waiting for visibility of element located by By.xpath: //*[#id="invoiceMenu"]/a (tried for 10 second(s) with 500 milliseconds interval)
Edit:
Was able to get some of the elements (angular ones) working with a few plugins for Chrome. Element Locator and ChroPath worked fantastic. Took some playing around with, but once I got one I was able to piece together the rest of them.

I would suggest that you open the chrome console on your browser and try to interact with the element in question e.g. using:
document.getElementById('someId').click()
If you are able to click on the element like that, then you can use javascript executor in your code as follows:
((JavascriptExecutor)driver).executeScript("document.getElementById('someId').click();");

Related

Selenium - Error getting WebElement within iFrame

I am building a small automated test script with Selenium Chrome WebDriver last version, but now I am facing an issue when I try to get a WebElement within an iFrame, even when I switch to it.
This is the way HTML is built:
As you can check, there is another page "encrusted" inside iFrame, and the button is defined below (it's the part I selected):
This is the way I am using to get the WebElement (obviously failing):
WebElement frameAperturar =
driver.findElement(By.xpath("//iframe[#title='Aperturar']"));
driver.switchTo().frame(frameAperturar);
asociarSiniestroButton = driver.findElement(By.xpath("//button[#aria-label='Asociar Siniestro']"));
asociarSiniestroButton.click();
This is the exception I got when I tried to get the WebElement:
no such element: Unable to locate element: {"method":"xpath","selector":"//button[#aria-label='Asociar Siniestro']"}
(Session info: chrome=60.0.3112.113)
Do you know how I can get an element of the page inside the iFrame after I switch to the frame?
You can actually select an iFrame using the below methods:
frame(index)
frame(Name of Frame [or] Id of the frame)
frame(WebElement frameElement)
defaultContent()
So you can switch by passing the any above information about the frame. Yes you need to switch every time according to require action.
Example:
driver.SwitchTo().Frame(0);
driver.SwitchTo().Frame("top");
.... Perform your action on frame
driver.SwitchTo().defaultContent();
driver.SwitchTo().Frame("navigation");
.... Perform your action on frame
driver.SwitchTo().defaultContent();
Try below XPath
//span[#class='apexButtonText' and contains(.,'Asociar Siniestro')]
OR
//span[contains(text(),'Asociar Siniestro')]
OR
//span[#class='apexButtonText'][contains(text(),'Asociar Siniestro')]
OR
//button[#aria-label='Asociar Siniestro']//span[contains(.,'Asociar Siniestro')]
I am new to selenium but seems like your button is actually 'span' and xpath wont work like this, try //span[contains(text(),'Asociar Siniestro')]
Use this xpath
//span[#class='apexButtonText'][contains(text(),'Asociar Siniestro')]

Element not clickable using Selenium webdriver with Chrome (same code:works fine using firefox)

Using selenium-2.44.tar.gz and chrome for automating test cases:Very strange my code works fine using Firefox 33 but fails using Google Chrome:
"WebDriverException: Message: u'unknown error: Element is not
clickable at point(57, 161). Other element would receive the click: ...\n
(Session info: chrome=42.0.2311.135 )\n (Driver info:
chromedriver=2.9.248315,platform=Windows NT 6.1 SP1 x86_64)'"
self.driver.find_element_by_xpath(".//[#id='searchMessagstoryBtn']").click()
any idea? shouldnt it work better with chrome one wonders since webdriver is Google code nowdays or am I wrong!!!
Unlike firefox, to use chromedriver you have to download chromedriver from http://www.seleniumhq.org/download/ and had to give path in your code.
You can use the below code, to use chrome driver in java or in python
Java:
public void testGoogleSearch() {
// Optional, if not specified, WebDriver will search your path for chromedriver.
System.setProperty("webdriver.chrome.driver", "/path/to/chromedriver");
WebDriver driver = new ChromeDriver();
driver.get("http://www.google.com/xhtml");
Thread.sleep(5000); // Let the user actually see something!
WebElement searchBox = driver.findElement(By.name("q"));
searchBox.sendKeys("ChromeDriver");
searchBox.submit();
Thread.sleep(5000); // Let the user actually see something!
driver.quit();
}
Python:
import time
from selenium import webdriver
driver = webdriver.Chrome('/path/to/chromedriver') # Optional argument, if not specified will search path.
driver.get('http://www.google.com/xhtml');
time.sleep(5) # Let the user actually see something!
search_box = driver.find_element_by_name('q')
search_box.send_keys('ChromeDriver')
search_box.submit()
time.sleep(5) # Let the user actually see something!
driver.quit()
It seems to be a bug in ChromeDriver.
http://code.google.com/p/selenium/issues/detail?id=2766
Try this workaround solution from form #27. I hope it would help you:
I ran into this same issue as well with Chrome...clicking the element
works fine in firefox but not in Chrome...the fix is pretty easy
though, all you have to do is scroll the element into view before
clicking it, and you won't run into this problem in Chrome. Here's the
code i use:
IWebElement elementToClick = ;
// Scroll the browser to the element's Y position (driver as
IJavaScriptExecutor).ExecuteScript(string.Format("window.scrollTo(0,
{0});", elementToClick.Location.Y));
// Click the element elementToClick.Click();
Hope this helps anyone else who runs into this issue
#FindBy(xpath = "//[#id='searchMessagstoryBtn']")
private WebElement Search_btn;
public WebElement getSearchBtnClick() {
return Search_btn;
}
public void Click_Search_Btn() {
//click the search button
TimeUnit.SECONDS.sleep(3);
getSearchBtnClick().click();
}

Share Target and JumpListItemBackgroundConverter

I've added the Share Target declaration to my app for the data format WebLink and everything works as expected. However, when I add a JumpListItemBackgroundConverter or JumpListItemForegroundConverter anywhere in the app, the app hangs on the splash screen when you enter the app using the Share from IE. No exception, no crash, the debugger doesn't even stop. All I get is a cryptic error in the output window, "The program '...' has exited with code -1073741819 (0xc0000005) 'Access violation'." The documentation for those converters say they're fine with universal apps, just that they've been moved to a different namespace. Has anyone been able to get these two things to work in the same app? If so, where did I go wrong? Or is there something better than those two converters to get the LongListSelector look and feel?
Steps to reproduce:
Create a new universal app. I chose hub.
Add a share target of format WebLink to the appxmanifest declarations.
Add a new page to point the share contract to.
Add the OnShareTargetActivated code to app.xaml.cs to open the new page. See code below
Add a JumpListItemBackgroundConverter to the resources of the main page of the app. You don't need to apply it to anything, just declaring it is enough to break the sharing.
Go to IE and share a link. It should hang on the splash screen.
Code for app.xaml.cs:
protected override async void OnShareTargetActivated(ShareTargetActivatedEventArgs args)
{
// Replace SharePage with the name of the share target page
var rootFrame = new Frame();
rootFrame.Navigate(typeof(SharePage), args.ShareOperation);
Window.Current.Content = rootFrame;
Window.Current.Activate();
}
It turns out this is a bug in the emulator. It works if you test on a physical device.
MSDN Forum - JumpListItemBackgroundConverter and Share Target in Windows Phone 8.1

Unhandled exception when firing WinRT 8.1 WebView ScriptNotify

I'm trying to create an MVVM Caliburn-based WinRT 8.1 app (I know that CM won't be perfectly compatible with 8.1 until version 2.0 is out, but the error does not seem to be related, as it is raised also when the handler is placed in the view code behind). One of its views contains a WebView control, whose content is set via NavigateToString (HTML contents come from app's installed assets). The HTML loaded into this control includes several hyperlinks, most of them representing cross-references to other asset-based HTML content. So when users click the link I want to override the standard navigation action, get my viewmodel notified, and let it load another HTML content from the app assets.
Here is what I did, following the post Open links in external browser in WebView (WinRT):
in the XAML code, I added to the WebView control an attribute for attaching the ScriptNotify event to my VM: cal:Message.Attach="[Event ScriptNotify] = [Action GetFromLink($eventArgs)]" (see https://caliburnmicro.codeplex.com/wikipage?title=All%20About%20Actions).
in my VM, the method signature is public void GetFromLink(NotifyEventArgs e).
whenever my VM loads some HTML into the WebView, it first injects a script in the HTML head which replaces the click handler of each anchor representing a cross-reference (all these anchors are marked by a class="xref" attribute). This script is hold in a constant in my VM:
private const string SCRIPT = "for (var i = 0; i < document.links.length; i++) {" +
"var className = document.links[i].getAttribute(\"class\");" +
"if (className && className === \"xfer\") {" +
"document.links[i].onclick = function() {" +
"window.external.notify('url:' + this.href);" +
"return false;" +
"}}}";
Now, when I launch the app, load an item containing one of these xref's and click on it, I get an unhandled exception telling me that "navCancelInit is undefined". I suppose this error is surfacing from JS code, but I cannot see where and how this function should be defined.
According to http://msdn.microsoft.com/library/windows/apps/br227713, I do not need any additional step for ScriptNotify when HTML has been loaded via NavigateToString. Could anyone suggest a solution?
I got an answer from a MS guy about this, so credit is not mine for this answer: it is a timing issue. I must ensure that the page has fully loaded before running the script which changes the DOM; pretty simple, if you think. Just moving the script at the end of the page, or wrapping it in an onload handler, should make the trick. Hope this can save some hair-pulling to others!
If you listen to this event: http://msdn.microsoft.com/en-us/library/windows/apps/windows.ui.xaml.controls.webview.domcontentloaded.aspx WebView.DOMContentLoaded event, All of the script should be loaded in the WebView and you should be able to access and execute, if you are trying to do this before the scripts won't be loaded.

Should all elements return true on isDisplayed() after a selenium Webdriver get()?

WebDriver get() and isDisplayed() methods are not working as I expected.
As for the doc:
This is done using an HTTP GET operation, and the method will block
until the load is complete
As mentioned in other questions like this Wait for page load in Selenium , the get method should wait for the page to load.
But after running get(), isDisplayed() method from RenderedWebElement does not always return true on some elements.
What are the possible causes?
I'd like some elaboration on the difference between being loaded and being displayed in the context of webdrivers.
In the latest UI frameworks/APi you can hide an element on a page.
For ex. Consider a page having 5 elements. When page is loaded only 3 elements will be shown on the page, the other 2 will be hidden and on taking some action the other 2 elements will be shown.
An example you can check under the demo section in following links:
Show element link: http://api.jquery.com/show/
Hide element link: http://api.jquery.com/hide/
When you use webDriver get() method, webdriver will wait for page to load i.e. it waits for all the html content of the page to be loaded onto the browser. This does not means that all the elements are visible.
When you use isDisplayed() webdriver checks whether the said element is Displayed on the page or not. If you know that the element may be hidden on the page when running your test-cases its a good approach to verify whether the element is displayed or not. Else your test script fails with a error "Element not displayed to take an action"
Hope this helps.
isDisplayed() seems to me not so good approach. get some ideas from wait: exlplicit and implicit wait mechanisms:
Explicit wait
WebDriverWait.until(condition-that-finds-the-element)
Implicit wait
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
Explicit Waits:
WebDriver driver = new FirefoxDriver();
driver.get("http://somedomain/url_that_delays_loading");
WebElement myDynamicElement = (new WebDriverWait(driver, 10))
.until(new ExpectedCondition<WebElement>(){
#Override
public WebElement apply(WebDriver d) {
return d.findElement(By.id("myDynamicElement"));
}});
Implicit Waits:
WebDriver driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("http://somedomain/url_that_delays_loading");
WebElement myDynamicElement = driver.findElement(By.id("myDynamicElement"));
The example what you have given both do exact same thing..
In Explicit wait, WebDriver evaluates the condition every 500
milliseconds by default ..if it is true, it comes out of loop
Where as in ImplicitWait WebDriver polls the DOM every 500
milliseconds to see if element is present..
Difference is
1. Obvious - Implicit wait time is applied to all elements in your
script but Explicit only for particular element
2. In Explicit you can configure, how frequently (instead of 500
millisecond) you want to check condition.
3. In Explicit you can also configure to ignore other exceptions than
"NoSuchElement" till timeout..
you can get some more info here
Also I use fluent wait mechanism for waiting elements get rendered on the page. Actually you pass either css selector either xpath to the function and simply get web element.
public WebElement fluentWait(final By locator){
Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
.withTimeout(30, TimeUnit.SECONDS)
.pollingEvery(5, TimeUnit.SECONDS)
.ignoring(NoSuchElementException.class);
WebElement foo = wait.until(
new Function<WebDriver, WebElement>() {
public WebElement apply(WebDriver driver) {
return driver.findElement(locator);
}
}
);
return foo; } ;
fluent wait description
hope this comes clear now)