简体   繁体   中英

size() option is missing using Selenium webdriver through Java

have been following some classes to improve my automation skills with Selenium Webdrive. I don't have size() method as an option when trying to count the numbers of links inside a page.

Am I missing some jars? Import libraries?

java public static void main(String[] args) throws InterruptedException {
        System.setProperty("webdriver.chrome.driver", "/Users/Follo/Dropbox/Chrome Drivers/chromedriver");
        ChromeOptions options = new ChromeOptions();
        options.addArguments("--start-maximized");
        // options.addArguments("--headless");
        WebDriver driver = new ChromeDriver(options);
        driver.get("URL");
        WebElement link = driver.findElement(By.tagName("a"));
        link.size()
        // .size do not appear as an option in the dropdown menu
        System.out.println(link.size());
        driver.quit();
    }
}

Use "findElement s " instead of "findElement". It returns list of elements so you can iterate through them.

The difference is that findElement returns first matched element and findElements return list of all matched elements

size()

The size() method of List interface in Java is used to get the number of elements in this list. That is, this method returns the count of elements present in this list container.

So essentially, the variable link which is of type WebElement won't support the size() method. So you have to change the type of the variable link as List and populate the List using findElements() method and you can use the following solution:

List<WebElement> link = driver.findElements(By.tagName("a"));
System.out.println(link.size());
    ArrayList<WebElement> firstLinkurl = (ArrayList<WebElement>) 

    driver.findElements(By.xpath("write your xpath here"));

    System.out.println(link.size());

    firstLinkurl.get(0).click();//also with this you can also click any link on the page just by providing the index number.

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