In my test project, I have a static class that contains a number of methods for basic interactions with WebElements. I have two separate methods for clicking a WebElement, one that uses the WebElement.click() method:
public static void click(WebElement element, WebDriverWait w) {
if (element == null) {
return;
}
try {
w.until(ExpectedConditions.elementToBeClickable(element)).click();
} catch (TimeoutException ex) {
Assert.fail("Test failed, because element with locator: " + element.toString().split("->")[1] + " was not found on the page or unavailable");
}
}
and one that uses the Actions.click(WebElement).build().perform() method:
public static void click(WebElement element, Actions a, WebDriverWait w) {
if (element == null) {
return;
}
try {
a.click(w.until(ExpectedConditions.elementToBeClickable(element))).build().perform();
} catch (TimeoutException ex) {
Assert.fail("Test failed, because element with locator: " + element.toString().split("->")[1] + " was not found on the page or unavailable");
}
}
I also have a method for finding and then clicking an option from a menu:
public void selectItem(IMenuButton button) {
for (WebElement item : w.until(ExpectedConditions.presenceOfAllElementsLocatedBy(By.cssSelector("*[role='menuitem']")))) {
if (item.findElement(By.tagName("span")).getText().trim().equalsIgnoreCase(button.getButton())) {
// This throws StaleElementReferenceException
Interaction.click(item, a, w);
// This works
Interaction.click(item, w);
return;
}
}
Assert.fail("No menu item found for: " + button.getButton());
}
When I use Interaction.click(item, w), it works, but Interaction.click(item, a, w) throws StaleElementReferenceException, and I can't figure out why. I need the method that uses Actions.click() in case the option needs to be scrolled into view. Any ideas?
Selenium 4
Chromedriver 99
Java
Usually, when you scroll down or up - the DOM changes. StaleElementReferenceException means that an element you once found has been moved or deleted. When going over elements inside a loop, very often elements inside a dropdown or scrollView, you need to find them all over again. Otherwise you will get this exception over and over again.
Try to do this:
try {
Interaction.click(item, a, w);
} catch (StaleElementReferenceException sere) {
// re-find the item by ID, Xpath or Css
item = driver.findElementByID("TheID");
//click again on the element
Interaction.click(item, a, w);
}
Related
I'm trying to click on element by text from list of elements, but sometimes elements could have the same text and if statement not executed.
public void clickByText() {
String myText = "Text1";
List<WebElement> elements = driver.findElements(myElements);
for (WebElement e : elements) {
if (e.getText().equals(myText)) {
e.click();
break;
} else {
System.out.println("not exists");
break;
}
}
}
Maybe don't look for the text by equals, use contains.
Remove the break from your code, this makes only the else or only the if block to run only once.
code example:
public void clickByText() {
String myText = "Text1";
List<WebElement> elements = driver.findElements(myElements);
for (WebElement e : elements) {
if (e.getText().contains(myText)) {
e.click();
} else {
System.out.println("not exists: " + e.getText());
}
}
}
I think it's an issue with duplicates. since list in Java can contains duplicates, whereas set do not. try the below code :
List<WebElement> elements = driver.findElements(By.cssSelector(""));
Set<WebElement> setElements = new HashSet<WebElement>(elements);
for (WebElement e : elements) {
// rest of your code
}
Appium is able to see and find elements that is not displayed on screen
I am trying to build a test automation project, I would like my driver to scroll down
and then perform some operation. but for some reason appium is able to find element even without scrolling down . I am not sure how appium is able to identify element that is not on screen and is only visible to naked eye when you scroll down. Anyone with similar issue found a workaround ?
I am using ExpectedCondition.visibilityOF(element) to determine if element is vsible on screen
public boolean verifyCoverage(String coverage, String value, String type) throws IOException, InterruptedException {
int counter = 0;
for (int i = 0; i < 15; i++) {
AndroidElement element = (AndroidElement) driver.findElementByAndroidUIAutomator("UiSelector().textContains(\"" + coverage + "\")");
//WebElement coverageOption= driver.findElementByXPath("//android.widget.Button[contains(text(),'"+coverage+"')]");
if (AndroidUtilities.waitForVisibility(driver, element)) {
return true;
}
else {
System.out.println ("Cannot see");
return false;
}
}
public static boolean waitForVisibility(AndroidDriver<WebElement> driver, AndroidElement AndroidElement){
try{
// driver.findElementByAndroidUIAutomator("UiSelector().resourceId(\""+targetResourceId+"\")");
WebDriverWait wait = new WebDriverWait(driver, 60);
wait.until(ExpectedConditions.visibilityOf(AndroidElement));
boolean isElementPresent = AndroidElement.isDisplayed();
return isElementPresent;
}catch(Exception e){
boolean isElementPresent = false;
System.out.println(e.getMessage());
return isElementPresent;
}
}
As an answer i would recommend you to use visibilityOfElementLocated instean of visibilityOf.
Plus, if you want to check an element for the existence without getting exceptions, try to take that approach:
if (!((AndroidDriver)driver).findElementsByAndroidUIAutomator("UiSelector().textContains(\"" + coverage + "\")").isEmpty()) {
//some logic when element is located
} else {
//scroll to the particular element
}
You can try these two solution within the page it will able to scroll to the element and do your actions .
MobileBy.AndroidUIAutomator("new UiScrollable(new UiSelector().scrollable(true).instance(0)).scrollIntoView(new UiSelector().textContains(\""+element+"\").instance(0))"));
MobileBy.AndroidUIAutomator("new UiScrollable(new UiSelector().scrollable(true).instance(0)).scrollIntoView(new UiSelector().textMatches(\"" + NumbersCount + "\").instance(0))"));
I get Stale Element Reference Exception.If I can single click.
I want to click on element until or 5 times find the object.
How can I have try catch block loop until click or element found?
I want it to attempt to click on element for 5 times before failing it.
I use below code but not working.
Click Method:
public void click1(WebDriver driver, WebElement element, String name) {
int attempts = 0;
while(attempts < 5) {
try {
element.click();
Add_Log.info("Successfully clicked on " + name);
Reporter.log("Successfully clicked on " + name);
break;
} catch (Exception e) {
try {
JavascriptExecutor executor = (JavascriptExecutor) driver;
executor.executeScript("arguments[0].click();", element);
Add_Log.info("Successfully clicked on " + name);
Reporter.log("Successfully clicked on " + name);
break;
} catch (Exception e2) {
Add_Log.info("Not able to click " + name);
Reporter.log("Not able to click " + name);
TestResultStatus.Testfail = true;
Assert.fail();
}
}
attempts++;
}
}
This is actually as easy as changing the loop condition from attempts < 5 to true and removing the attempts++; line. At least that's what I understood from your question. If that's not what you're looking for, try rephrasing the question more clearly.
I would write it more like the below. You attempt to do a normal click 5 times with a brief pause between attempts. If an exception is thrown, it's eaten and another attempt is made. If none of those 5 are successful, you make a single attempt to click on it using JS. If that fails, then log failures, etc.
public void click1(WebDriver driver, WebElement element, String name) {
int attempts = 0;
while(attempts < 5) {
try {
element.click();
Add_Log.info("Successfully clicked on " + name);
Reporter.log("Successfully clicked on " + name);
return;
} catch (Exception e) {
}
attempts++;
Thread.Sleep(500); // brief pause between attempts
}
try {
JavascriptExecutor executor = (JavascriptExecutor) driver;
executor.executeScript("arguments[0].click();", element);
Add_Log.info("Successfully clicked on " + name);
Reporter.log("Successfully clicked on " + name);
return;
} catch (Exception e2) {
Add_Log.info("Not able to click " + name);
Reporter.log("Not able to click " + name);
TestResultStatus.Testfail = true;
Assert.fail("Not able to click " + name);
}
}
NOTE: You probably would be better off waiting for the element to be clickable before attempting to click it. That would probably remedy most of your issues. You still may have an issue with some dialog/banner/spinner overlapping the element that you would need to deal with though... and you could deal with that with the 5 attempted clicks, etc.
I have a product page which has the sizes inside containers, i tried to list elements and get size by text but the list always returns zero, i tried the xpath of the parent and child and i get the same error, How can i list the sizes and select specific size ?
public void chooseSize(String size) {
String selectedSize;
List<WebElement> sizesList = actions.driver.findElements(By.xpath("SelectSizeLoactor"));
try {
for (int i = 0; i <= sizesList.size(); i++) {
if (sizesList.get(i).getText().toLowerCase().contains(size.toLowerCase()));
{
selectedSize = sizesList.get(i).getText();
sizesList.get(i).click();
assertTrue(selectedSize.equals(size));
}
}
} catch (Exception e) {
Assert.fail("Couldn't select size cause of " + e.getMessage());
}
It looks to me like the proper selector would be:
actions.driver.findElements(By.cssSelector(".SizeSelection-option"))
Try below options
List<WebElement> sizesList = actions.driver.findElements(By.xpath("//[#class='SelectSizeLoactor']"));
List<WebElement> sizesList = actions.driver.findElements(By.cssSelector(".SelectSizeLoactor"));
I found a quick solution i used part of the xpath with text() and passed the value of that text later then added the last of the xpath and it worked!
String SelectSizeLoactor = "//button[text()='"
public void chooseSize(String size) {
String selectedSize;
WebElement sizeLocator = actions.driver.findElement(By.xpath(SelectSizeLoactor+size.toUpperCase()+"']"));
try {
if (sizeLocator.getText().toUpperCase().contains(size.toUpperCase()));
{
selectedSize = sizeLocator.getText();
sizeLocator.click();
assertTrue(selectedSize.equals(size));
}
} catch (Exception e) {
Assert.fail("Couldn't select size cause of " + e.getMessage());
}
}
Using Selenium to gather text of all p elements within a specific div. I noticed while using List, Selenium scanned the whole DOM and stored empty text. So, I wanted to iterate through the DOM and only store values that are not equal to empty text via java.util.Iterator. Is this possible? Is there a more efficient way other than the List approach?
Iterator Approach:
public static boolean FeatureFunctionsCheck(String Feature){
try
{
Iterator<WebElement> all = (Iterator<WebElement>) Driver.Instance.findElement(By.xpath("//a[contains(text()," + Feature + ")]/ancestor::h3/following-sibling::div/div[#class='navMenu']/p"));
boolean check = false;
while(all.hasNext() && check){
WebElement temp = all.next();
if(!temp.getText().equals(""))
{
Log.Info("Functions: " + temp.getText());
all = (Iterator<WebElement>) Driver.Instance.findElement(By.xpath("//a[contains(text()," + Feature + ")]/ancestor::h3/following-sibling::div/div[#class='navMenu']/p"));
}
else
check = true;
}
return false;
}
catch(Exception e)
{
Log.Error("Failed()" + e);
return false;
}
}
Iterator Approach throws exception...
java.lang.ClassCastException: org.openqa.selenium.remote.RemoteWebElement cannot be cast to java.util.Iterator
List Approach Works, However Not Sure If This Is Efficient
public static boolean FeatureFunctionsCheck(String Feature){
try
{
List<WebElement> AllModelFunctions = new ArrayList<WebElement>();
Log.Info("[Test-235]: Selecting Feature");
for(WebElement element: AllModelFunctions){
if(!element.getText().equals(""))
{
Log.Info("Functions: " + element.getText());
}
}
return false;
}
catch(Exception e)
{
Log.Error("Failed()" + e);
return false;
}
}
findElement returns one WebElement. What you probably meant to do is to search for all elements with given xpath, using findElements:
Driver.Instance.findElements(...
Also the syntax is over-complicated. You can just get the list and iterate through it:
List<WebElement> elements = Driver.Instance.findElements(...);
for(WebElement element : elements) {
if(!element.getText().equals(""))
{
Log.Info("Functions: " + element.getText());
}
}
BTW I have to fully trust that Driver.Instance is an instance of the driver (typically in Java you don't have capitals for class instances, so I'm not sure if I understood it right). A more common syntax would be something like:
WebDriver driver = new FirefoxDriver(); // or another browser
driver.findElements(...);
// ...