简体   繁体   English

通过 Java 使用 Selenium webdriver 缺少 size() 选项

[英]size() option is missing using Selenium webdriver through Java

have been following some classes to improve my automation skills with Selenium Webdrive.一直在学习一些课程,以提高我使用 Selenium Webdrive 的自动化技能。 I don't have size() method as an option when trying to count the numbers of links inside a page.尝试计算页面内链接的数量时,我没有size()方法作为选项。

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".使用“findElement s ”而不是“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区别在于 findElement 返回第一个匹配的元素, findElements 返回所有匹配元素的列表

size()尺寸()

The size() method of List interface in Java is used to get the number of elements in this list. Java 中 List 接口的size()方法用于获取此列表中元素的数量。 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.因此,本质上, WebElement类型的变量链接将不支持size()方法。 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并使用findElements()方法填充List ,您可以使用以下解决方案:

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.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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