size() option is missing using Selenium webdriver through Java

别来无恙 提交于 2021-02-17 06:48:24

问题


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();
    }
}

回答1:


Use "findElements" 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




回答2:


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



回答3:


    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.


来源:https://stackoverflow.com/questions/56363108/size-option-is-missing-using-selenium-webdriver-through-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!