简体   繁体   中英

How to access the first element of an array and click the same at runtime using selenium web driver?

I have a drop list as id="product-size" and the items S,M,L,XL.

<select id="product-size" onchange=" addToWishList();">
 <option>Select</option>
 <option id="2119362" value="4">S</option>
 <option id="2119363" value="7">M</option>
 <option id="2119364" value="8">L</option>
 <option id="2119365" value="4">XL</option>
</select>

I have used an array to store these items and at Runtime I need to access the first element 'S'.The problem I am facing is ,I was not able to click on the first element S at runtime. I have written the code as follows :

driver.get("https://m.staging.karmaloop.com/product/The-Infinity-Tee/407819");
WebElement j =driver.findElement(By.id("product-size"));
String text = j.getText(); 
String[] DDLcount =text.split("\n");
for (int i=1;i<=DDLcount.length-1;i++)
    {       
    driver.findElement(By.xpath(Testconfiguration.size_dropdown_10deep)).click();
    Thread.sleep(5000);
    driver.findElement(By.name(DDLcount[i])).click(); 
    }

Can anyone help me to sort out this problem ?

From the code you've supplied, you're using an invalid selector for the Options.

They don't appear to have a name attribute

Aside from modifying the loop, you could make the operation faster if the DOM isnt reconstructed.

WebElement selectBox = driver.findElement(By.xpath(Testconfiguration.size_dropdown_10deep));
List<WebElement> options = selectBox.findElements(By.tagName("option"));
for ( WebElement option : options )
{      
    selectBox.click();
    option.click();
}
By locator = By.id("product-size");
Select select = new Select(webdriver.findElement(locator));

You can you use any of the three following options to select an item from dropdown

select.selectByIndex(index); // Give Index as parameter
select.selectByValue(value); // Give the value of the option tag 
select.selectByVisibleText(value); // Give the visible text as parameter
 WebElement element =driver.findElement(By.id("product-size"));
Select sel = new Select(element);
List<WebElement> items = sel.getOptions();
boolean stringExits = false;
for(int i =0; i<items.size(); i++)
{
    String text = items.get(i).getText();
    if(text.equals("S"))
    {
         stringExists = true;
         break;
    }
}

if(stringExits)
{
     System.out.println("The string exists");
}else
{
     System.out.println("The string does not exist");
}

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