Appium is able to see beyond what is displayed on screen - java

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

Related

Selenium String into WebElement for iteration

I have defined my web elements as following:
By elementABC= By.xpath("//div[#id='ABC']");
By elementDEF= By.xpath("//div[#id='DEF']");
Now I have a method that should take the the name as String (elementABC,elementDEF) and verify the presence of element. The String is being read from external file excel. The reason is so that I can iterate over multiple elements on a web page and just verify there presence.
public static boolean verifyElementPresent(String e) {
boolean result= false;
WebElement webObj=e; // this is where I'm facing trouble
WebElement element = driver.findElement(webObj);
//WebElement element = driver.findElement(By.xpath("elementDEF"));
if (element.isDisplayed() ) {
result=true;
}
else {
result=false;
}
return result;
}
My problem is that I want to read a string and then be able to convert it into Web Element. The value of e being passed in my method is elementABC, elementDEF. And in next line I want to convert into WebElement.
WebElement webObj=e;
WebElement element = driver.findElement(webObj);
I came across a similar post on stackoverflow and noticed users have mentioned there is no good way to convert WebElement into String. But I still wanted to know if there is any other way of implementing this.
convert String to WebElement
You should define webObj as By not WebElement.
To prevent the script from error when element not found, you still need to use try catch, like this:
public static boolean verifyElementPresent(String e) {
boolean result= false;
By webObj = By.xpath("//div[#id='" +e +"']");
WebElement element = driver.findElement(webObj);
try {
if (element.isDisplayed()) {
result=true;
}
} catch (Exception e2) {
// TODO: handle exception
}
return result;
}

How to improve resursive function performance?

I created a recursive function. The goal of this function is to browse all frames til to find the element. But it is very slow.
Please find below the function:
private WebElement browseFramesToFindElement(By locator) {
WebElement element = null;
if (isElementPresent(locator, 1))
element = this.driver.findElement(locator);
if (element == null) {
List<WebElement> frames = this.driver.findElements(By.xpath("//frame"));
int i = 0;
while (i < frames.size() && element == null) {
this.driver.switchTo().frame(this.driver.findElement(By.xpath("//frame[#id = '" + frames.get(i).getAttribute("id") + "']")));
element = browseFramesToFindElement(locator);
if (element == null)
driver.switchTo().parentFrame();
i++;
}
}
return element;
}
private boolean isElementPresent(By by, int secToWait) {
this.driver.manage().timeouts().implicitlyWait(secToWait, TimeUnit.SECONDS);
try {
this.driver.findElement(by);
return true;
} catch (NoSuchElementException e) {
return false;
}
}
Could you please tell me if it is possible to improve performance? And How? Thank you in advance.
I am not sure your performance issues are related with that you have ineffective recursion algorithm. I would suggest you to:
Change xpath locators to css locators (likely will help)
Tune wait timeouts and watch for the result (not sure but that might give a direction)

Handling alerts using if/else in Java

How to handle the alerts using if/else commands? If alerts comes up do accept/dismiss, if not proceed further. I was trying with below code but an error at (r==true) says incompatible type.
bool r = driver.findElement(By.xpath("//div[contains(text(),'javax.baja.sys.ActionInvokeException')]"));
if (r = true) {
driver.switchTo().alert().accept();
} else {
Actions click2 = new Actions(driver);
WebElement dclick2 = driver.findElement(By.xpath(".//span[text()='Bluemix_As_Device']"));
click2.moveToElement(dclick2).doubleClick().build().perform();
}
The incompatible type is for the reason that
driver.findElement
would return a WebElement type and not a boolean(that's java). You might want to change the code to:
try {
WebElement r = driver.findElement(By.xpath("//div[contains(text(),'javax.baja.sys.ActionInvokeException')]"));
driver.switchTo().alert().accept(); // this would be executed only if above element is found
} catch (NoSuchElementException ex) {
// since the element was not found, I 'm still doing some stuff
Actions click2 = new Actions(driver);
WebElement dclick2 = driver.findElement(By.xpath(".//span[text()='Bluemix_As_Device']"));
click2.moveToElement(dclick2).doubleClick().build().perform();
}
As r is of boolean type so there is no need to write if(r == true) or if(r == false) you can directly write if(r) and java will understand the code.
driver.findElements will check the existence of the object and will return 1 if exist else zero.
So in your case though the alert exist or not, it will handle and based on size it will execute next step. Hope this helps in your case.
int r= driver.findElements(By.xpath("//div[contains(text(),'javax.baja.sys.ActionInvokeException')]")).size();
if(r!=0){
driver.switchTo().alert().accept();
} else {
Actions click2 = new Actions(driver);
WebElement dclick2 = driver.findElement(By.xpath(".//span[text()='Bluemix_As_Device']"));
click2.moveToElement(dclick2).doubleClick().build().perform();
}

Using Iterator with Java Selenium WebDriver

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(...);
// ...

how to click a result from google search that is not on first page with selenium java

I am trying to navigate through search results from google with selenium webdriver. I have a interface for user to inset word to search and site title to choose. If the result is not on the first page the driver should go to next page to look for the site, and if not there than to next page and so on..
Somehow I don't manage to get beyond the second page end if I did get to the second page and the right site is there, the driver doesn't click on it.
Here is some of the code in Java:
private void setLoopNum(int l){
String getText = urlText.getText();
String getSiteName = linkToChoose.getText();
System.setProperty("webdriver.chrome.driver", "C:\\selenium-2.44.0\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize(); //Maximize window
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
for(int i=0;i<l;i++){
//WebDriver driver = new FirefoxDriver();
driver.get("http://google.com");
//driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
WebElement element1 = driver.findElement(By.name("q"));
element1.sendKeys(getText);
element1.submit();
//driver.manage().timeouts().implicitlyWait(30,TimeUnit.SECONDS); //wait for page to load
//try{
boolean flag = false;
String page_number = "1";
while(! flag){
//get all the search results
List<WebElement> linkElements = driver.findElements(By.xpath("//h3[#class='r']/a"));
for(WebElement eachResult: linkElements){
if(eachResult.getAttribute(getSiteName).equals(getSiteName)){
eachResult.findElement(By.xpath("//a[#href='" + getSiteName + "']")).click();;
flag =true;
}else{
driver.findElement(By.xpath("//a[#id='pnnext']/span")).click();
linkElements.clear(); //celean list
break;
} //end else
}
}//end while loop
//}catch(Exception e){
// System.out.println("Error!");
// }
}
driver.quit(); //clear memory
}
Three things that you are missing in your code:
Firstly, in your code you are looking for only first element in your list.
Secondly, in getAttribute you are passing link instead of href:
if(eachResult.getAttribute(getSiteName).equals(getSiteName)){
it should be:
if(eachResult.getAttribute("href").equals(getSiteName)){
Thirdly, on clicking next the page is loaded via Google Ajax Api. Thus webdriver click will never block the execution of your code and will load linkElements with previous page links only. To avoid this let the driver get refreshed or put some wait for certain condition in your code.
Can u try out with this code:
WebDriverWait wait = new WebDriverWait(driver, 10)
while (!flag) {
// get all the search results
linkElements = wait
.until(ExpectedConditions
.presenceOfAllElementsLocatedBy(By
.xpath("//h3[#class='r']/a")));
for (WebElement eachResult : linkElements) {
if (eachResult.getAttribute("href").contains(getSiteName)) {
eachResult.click();
flag = true;
break;
}
}
if (!flag) {
driver.findElement(By.xpath("//a[#id='pnnext']/span[1]"))
.click();
pageNumber++;
linkElements.clear(); // celean list
wait.until(ExpectedConditions
.textToBePresentInElementLocated(
By.xpath("//td[#class='cur']"), pageNumber
+ "")); // Checking whether page number is changed as expected.
}
}// end while loop
EDIT:
List<WebElement> linkElements = new ArrayList<WebElement>();
ListIterator<WebElement> itr = null;
System.setProperty("webdriver.chrome.driver",
"webdrivers/chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize(); // Maximize window
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
driver.get("http://google.com");
WebElement element1 = driver.findElement(By.name("q"));
WebElement toClick = null;
element1.sendKeys(getText);
element1.submit();
// try{
int pageNumber = 1;
WebDriverWait wait = new WebDriverWait(driver, 10);
boolean flag = false;
while (!flag) {
linkElements = wait.until(ExpectedConditions
.presenceOfAllElementsLocatedBy(By
.xpath("//h3[#class='r']/a")));
itr = linkElements.listIterator(); // re-initializing iterator
while (itr.hasNext()) {
toClick = itr.next();
if (toClick.getAttribute("href").contains(getSiteName)) {
toClick.click();
flag = true;
break;
}
}
if (!flag) {
driver.findElement(By.xpath("//a[#id='pnnext']/span[1]"))
.click();
pageNumber++;
linkElements.clear(); // clean list
wait.until(ExpectedConditions.textToBePresentInElementLocated(
By.xpath("//td[#class='cur']"), pageNumber + ""));
}
}
driver.quit(); // clear memory
}
It looks like you're moving to the next page every time ANY of the WebElements in linkElements isn't what you're looking for. This will cause problems, as you need to relocate any elements that are re-rendered.
Give this a shot:
boolean found = false;
int page_number = 1; //If you need this as a string, you can make it one later
while(! found){
//get all the search results
List<WebElement> linkElements = driver.findElements(By.xpath("//h3[#class='r']/a"));
for(WebElement result: linkElements){
if(result.getAttribute("href").equals(getSiteName))
{
result.click();
found=true;
break;
}
}//End of foreach-loop
if(!found){
driver.findElement(By.xpath("//a[#id='pnnext']/span")).click();
page_number++;
}
}//End of while-loop
Also, you'll want to have some element-finding protection. Say that you search for something that has 0 results, or only one page of them (rare though that is). In the first case, you're lucky, because driver.findElements() should just return an empty list rather than throwing some exception, and the foreach loop just won't run, but in both cases, there won't be the anchor #pnnext, which will cause driver.findElement to throw an exception when you search for it. There are several ways to protect against this, such as writing a small wrapper function (IIRC, they have a simple implementation for findelementwithtimeoutwait() written on the Selenium website somewhere). I suggest you pick/write one and start using it, instead of the raw Selenium functions.

Categories

Resources