简体   繁体   中英

How to randomly click an element in the list (Android)using selenium+Appium?

Below code throws an array illegal out of bound exception

java.util.List <MobileElement> ele = driver.findElements(By.xpath("//*[@id='com.bankappointmentschedulingmobile:id/bankType'][@index=0]"));
System.out.println(ele.size());
Random rnd = new Random();
int rndInt = rnd.nextInt(ele.size());
((org.openqa.selenium.WebElement) ele.get(rndInt)).click();

Elements in the UI automator:

在此处输入图片说明

You don't have to use XPath in above case because you have element ID. Also, you are adding a check for index=0, it means it will check elements only with index 0. In the below example, I am finding elements using ID = "bankType" and printing its size. While generating random number I have subtracted "1" because the index will start from 0.

List<WebElement> elementList = driver.findElements(By.id("bankType"));
System.out.println("Total elements : " + elementList.size());

Random rand = new Random();
int index = rand.nextInt(elementList.size()-1); // -1 because index will start from 0

elementList.get(index).click();

Used this approach with appium using ruby, but this one should be good if you have fewer elements and also since, both of my elements had different xpath's.

 And(/^I select the choice in cooking style$/) do
  style = 
['//UIAApplication[1]/UIAWindow[1]/UIACollectionView[1]/UIACollectionCell[1]/UIACollectionView[1]/UIACollectionCell[1]/UIAStaticText[1]]' , '//UIAApplication[1]/UIAWindow[1]/UIACollectionView[1]/UIACollectionCell[1]/UIACollectionView[1]/UIACollectionCell[2]/UIAStaticText[1]']
  cookingstyle = style.sample
  find_element(xpath: cookingstyle).click
  puts cookingstyle

end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM