简体   繁体   中英

Selenium webdriver - Iterate, find webelement and then click on it - how can I do that?

I'd like to find the webelement that has as the visible text "7000118777", however I don't know how to exactly find it in the list and then click on it.

When I iterate it shows that the index is -1 and I get the error of "productList.get(-1);"- this is not the correct one.

public void findProductAndAddToCart(String product) {

        List<WebElement> productList = SeleniumDriver.getDriver().findElements(By.className("bcom--txtBold"));

        for (WebElement webElement : productList) {
            String elements = (webElement.getAttribute("innerHTML"));
            int indexOfProduct = elements.indexOf("7000118777");

            System.out.println("Indeks produktu "+indexOfProduct);
        }
        productList.get(-1);

As you have not provided a link to url or screenshot of your html, this is what i understand from your question that you want to click on a element from a list where visible text is "7000118777". I also believe that you located the elements correct ie, your productList. Please refer the below code (Replace myDriver with your WebDriver):

 List<WebElement> productList = myDriver.findElements(By.className("bcom--txtBold"));
        for (int i=0; i< productList.size();i++) {
            String element=productList.get(i).getText();
            if(element.equals("7000118777"))
            {
                productList.get(i).click();
            } 

        }

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