I am working on a development script using Selenium and Appium and I'm running into the issue of the wrong element being picked up by the Selenium Locator.
Essentially, I want to click a button that has no ID assigned to it; so the only thing I have left to identify it by is its text.
public Element button1(){
By locator = By.xpath("//android.widget.TextView[#text='button1']");
return new xElement(driver.findElement(locator), locator);
}
This is my my locator method to get the button1 object. By the way, no other button on the screen has text anywhere close to button1's text. The method click called on the button has the format:
public void clickBtn1(){
button1().click();
}
The button being clicked essentially has the text "wheelbarrow". This is just to clarify that the button being pressed has text no where close to button1's value.
I have used UI automator multiple times to confirm button1's actual text value. The weird thing is the script works occasionally, so I'm not sure what the issue is.
I have also tried a "wait for enabled" method to account for race conditions.
Try using the Appium inspector to search for your button. You can type in the xpath and search for the element to see what it finds. The other nice thing about the inspector is you can see how the native control attributes map to the Appium attributes. 'text' may not be the attribute you actually want. Also, have you tried searching on properties on the Button itself (instead of TextView)?
If it's working occasional, First try to use different element other than xpath. Second, try to give some sleep command before you perform that action like
WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.visibilityOfElementLocated(ByLocator(locator)));
Related
After clicking on a link a modal appear where a close button exist. I tried to close the modal with below code but it's not working.
WebElement element = driver1.findElement(By.className("btn btn-secondary"));
if (element.isEnabled()) {
element.click();
} else {
System.out.println("Disable");
}
I can tell from your locator that you are at least getting the error,
Compound class names not permitted
By.className() expects a single class name but you have provided two which will cause the error above. Without the HTML, it's hard to say what the best locator might be but one that might work is the CSS selector,
By.cssSelector(".btn.btn-secondary")
As generic as this is, it's possible that there is more than one element that matches.
You might need to add a wait, especially since you are dealing with a modal dialog,
new WebDriverWait(driver).until(ExpectedConditions.elementToBeClickable(...)).click();
You probably want another wait to make sure that the dialog closes before the script continues.
I am trying to navigate through all the available pages in a website, at the beginning after scrolling to the second page I was getting exception that there is no such element on the web page, then I realize, at some point the css selector is changed in the website. Sometimes it is like that WebElement nextButton = driver.findElement(By.cssSelector("#pagination-head>a>div>span.hidden-xs.hidden-sm")); and sometimes WebElement nextButton = driver.findElement(By.cssSelector("#pagination-head > a:nth-child(3) > div > span.hidden-xs.hidden-sm")); My question is how I can handle this in selenium, I checked whether there is a method to check somehow whether a given webelement exist or not but I could no find any :/
You could use this cssSelector for both paths:
WebElement nextButton = driver.findElement(By.cssSelector("#pagination-head span.hidden-xs.hidden-sm"));
If its only these 2 options, you could work with a workaround if/else statement.
You could create a boolean checking if element can be found by your first findElement. If true, use your first code, else, use second code.
You can use if-else block if you are sure that the next button is identified only by those two locators. If in case on the third page the locator changes, your if-else block will not work. So, better approach is to go for xpath to identify the next button. You can use below sample code to locate your element
WebElement nextButton = driver.findElement(By.xpath(".//*[contains(text(),'(text on your next button)')]"));
nextButton.click();
Please replace "(text on your next button)" with the text displayed on your next button. The above code will perform the click operation on the element containing the text which you pass.
Hope this is helpful.
I'm trying to click on an element on a page; the element is clearly visible on screen. There is a toaster that might pop up, so I'm trying to write a defense: if the toaster is on screen, close the toaster first, then continue clicking through to the next page. I am using PageFactory, so I have an element to contain the toaster and one for the close button for the toaster. My "deal with toaster" method is as follows:
if (driver.findElements(By.cssSelector("#toaster")).size() > 0
&& toaster.isDisplayed()) {
toasterClose.click();
}
When I do this in chrome, however, I'm getting org.openqa.selenium.WebDriverException: unknown error: Element is not clickable at point (994, 758)
Pausing the test execution, I cannot see the toaster on the screen. I figure the devs must be hiding it by making it render in a far away, unscrollable location. So as a stopgap measure, I added a condition that if the x coordinate was greater than 800, don't click. With that in place, I get:
org.openqa.selenium.WebDriverException: unknown error: Element is not clickable at point (547, 725). Other element would receive the click: <div id="toaster">...</div>
What's going on? How can the toaster not be clickable but would somehow receive the click anyway? Firefox can handle the test just fine, with or without the 800 pixel workaround; it's only Chrome having this issue.
For Clarification: The goal of the test is NOT to click the toaster. The goal is to click another element on the page. The test reported that a toaster was in the way, so I attempted to write a step to close the toaster if it is displayed. I have not seen this toaster, so I'm not exactly sure what it is, but chrome keeps reporting that it's in the way. All our toasters site-wide use a basic template that includes a close button so the user can close the toaster, which is what I'm trying to click. Firefox never has this issue and does not report the existence of any toasters.
I'm calling it a toaster because that's what our site calls it, because that's what it's called in whatever framework we got it from (jQuery UI? Backbone?). If I pause execution, I cannot see any toasters at this point in the test, but jQuery tells me it exists and is visible. However, the element found with jQuery has just the default pieces of our toaster setup: a div, an empty div where the message should be, and the close button. Clearly it's not meant to be rendered at this time, but Chrome thinks it's in the way.
I'm assuming by "toaster" you mean some sort of javascript modal popup with a close button.
Identifying the correct problem
You're testing the existence and visibility of the #toaster element, but not the toasterClose element that you're clicking. There's no guarantee that just because one element exists and is displayed, another is as well. From the error, it appears that the #toaster element overlaps the toasterClose element, making it unclickable.
Troubleshooting clickability
Once you've properly selected toasterClose, manually use devtools and inspect to see why it's unclickable. Is it visible and unobstructed? Is the toasterClose element something of zero height/width? Is there dynamic JavaScript modifying the page post-load? Is it actually positioned in view of the page? (I've had elements render visibly at the edge of the window only to be obstructed by the browser's scroll bars.1)
Alternative
You should also see if you really need to use this toasterClose element. How does would a human close this popup? Would they press Escape? Would they click outside the popup window, on the overlay element? Do they do something else that triggers some sort of closeModal() javascript function? You can also do any of these things using Selenium.
Last Resort
One thing you can always do to remove such a popup is to run your own javascript to modify the DOM and remove the offending element(s) altogether:
driver.execute_script(<<-javascript)
var toaster = document.getElementById("toaster");
toaster.parentNode.removeChild(toaster);
var overlay = document.getElementById("modal_overlay");
overlay.parentNode.removeChild(overlay);
javascript
Future/Additional
If this is a regular issue for you, I would suggest wrapping this code in try/catches and a retry mechanism to make it resilient to javascript dynamically loaded elements.
1 Update
Just to elaborate on the scrollbar issue I had, because it turned out that it was a very similar problem to yours.
Here, the "I'm Feeling Lucky" button is out of view. If Selenium tries to click on it, first it will attempt to scroll it into view.
Here's an example of what Selenium would attempt to do. Notice how the button is now "in view".
However, Chrome on OSX is styled in such a way that the scrollbars are normally hidden. The moment that Selenium issues the scroll command, the scrollbars appear and the following click command fails to reach the button.
The solution was to use javascript to scroll the window manually:
page.execute_script(<<-javascript)
document.getElementById("gbqfsb").scrollIntoView(true);
// or if that doesn't work:
window.scrollTo(0, document.getElementById("gbqfsb").getBoundingClientRect().top);
javascript
Try the following code. Should work:
if (driver.findElements(By.cssSelector("#toaster")).size() > 0
&& toaster.isDisplayed()) {
Actions builder = new Actions(driver);
builder.moveToElement(toasterClose).moveByOffset(2,2).click().build().perform();
}
Can you close toaster using escape key from keyboard manually.
If you can than use following:
Actions action = new Actions(driver);
action.sendKeys(Keys.ESCAPE).build().perform();
It seems the toaster was partially rendered and fixed to the DOM just below the bottom edge of the screen, using position:fixed to stop it from showing up until it's ready to be populated with data and animated onto the screen. When chrome tried to click on links that were below the bottom edge of the screen, it predicted that it'd hit the toaster and didn't actually bother scrolling.
After some googling, I added the following utility function:
public static void ScrollElementIntoView(WebDriver driver, WebElement element) {
((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", element);
}
Then I call this method before clicking any link on that page, and voila, no more toaster problems!
In Selenium 2.37, I can click the "Open" item in a context menu, when I search for it in two steps:
Find a few WebElement's by searching for the following XPath:
td[#class=\"dijitReset dijitMenuItemLabel\" and " + "starts-with(#id,\"dijit_MenuItem_\")]
Then, for each WebElement in this List of WebElement's, I do
String s = we.getText(); if (s.equals("Open") == true) { ... }
This works fine.
My problem is when I do the above "in one step", by including the text search in the XPath:
td[#class=\"dijitReset dijitMenuItemLabel\" and " +
"starts-with(#id,\"dijit_MenuItem_\") and text()=\"Open\"]
In this case, I do find the "Open" entry in the context menu, and I can click on it. So far, so good. So for finding the Open entry ONCE, and clicking on it ONCE, both the above methods work fine.
The problem is that when I use the second method, then the NEXT time I want to bring up the context menu (for a different document) and click the Open menu item, the context menu appears. BUT the mouse doesn't move down to the Open menu item, so the click never happens.
This is all during a single WebDriver run, so the result is that I can open one document (the first document I see), its context menu appears, the mouse moves to the Open context menu item, and clicks it. But then (same WebDriver run), when I get to the second document, the right-click happens, and the context menu appears, BUT the mouse does NOT move down to the Open menu item, so the click never happens.
Of course, for now, I'm using the first method. But I would really prefer to use the second method, since if everything (including the text() match) is in a single XPath expression, I can look for that element in a WebDriverWait.
It's as if the Open menu item is (somehow) destroyed, detached from the DOM, or whatever, when the more complex XPath is used to find it.
I only have this problem with items in CONTEXT menus.
Any advice would be appreciated!
You didn't send complete example of your problem but for what I understand you did not wait something to be loaded (specially if you do this on SPA it's some onClick binding). Try the first approach with hard-coded wait for one second, if it click then you need to find a way to check that the Open element have binded click. You can add some additional wait.until like:
wait.until(ExpectedConditions.elementToBeClickable(By.id<locator>));
Also you can create some extended expected conditions which inject JavaScript to the browser and return is click is binded.
I am automating a code using selenium 2.0. I select one (or several) user(s) from a list. Then I click on an add button which makes the user name(s) visible on a grid. Each user will have a valid Xpath when visible on the grid. However, even after erasing all user names from the grid which actually disappears if there is no user names displayed, the Xpath still does not return null. I am using Xpath to check if it returns null when the object (user name) is not visible, but it does not work as expected. Is there any other way to solve my problem? I am pretty new with Selenium. I am using selenium 2.0. Bellow is a section of my code. Your help will be very appreciated.
//Check if user is present on the grid
By checkuser = By.xpath( ".//*[#id='sharing_list']/tbody/tr/td[1]/span");
//if the grid is not empty, which means the grid is visible...
if(null!=checkuser) //where the problem is!!
{
//Click the button to erase the names in the grid, then the grid desapears
webDriver.findElement(By.xpath("//*[#id='sharing_list']/tbody/tr/td[4]/span")).click();
Thread.sleep(2000);
//more code
//............
}
I can see two things happening here:
First is that your XPath is generic enough that it is selecting some other element that isn't a user. To see if this is the case, then in Chrome, go to the page and do the necessary actions to get it in the state you want. Next, press Ctrl-Shift-J, click on Console, and type in $x("//*[#id='sharing_list']/tbody/tr/td[4]/span"). Chrome will then show you which element your selector is selecting.
Your task then, is to identify if its selecting some other element, or whether the element is just not visible. It is definitely possible to have an element on a page, but not visible, and WebDriver WILL select invisible elements (unless you are doing By.linkText()). If you want to check to see if an element is visible do a element.isDisplayed().