Search code examples
javahtmlseleniumfor-loophref

JAVA Selenium - getting hrefs from html in a loop


I'm trying to get hrefs of few similiar elements on the page and then find the last created (max) id in these hrefs. I have got a loop but it only finds the first element and does not search for the rest of them. Do you know what's written wrong in it?

ArrayList<Integer> tablicas = new ArrayList<Integer>();
    int i;
    for(i = 0; i < 90; i++) {
        String s = driver.findElement(By.cssSelector("a.linkOffer")).getAttribute("href");
        String p = s.substring(19, s.length());             
        int numer = Integer.parseInt(p);    
        System.out.print(p);

        for(int indeks : tablicas) {
            if(indeks == numer) {
                continue;
            } else {
                tablicas.add(numer);
        }
        }
        } System.out.print(tablicas);

Solution

  • There are multiple errors in your code snippet.

    driver.FindElement() will return one WebElement. - Since your css selector is identincal for each iteration of the loop, it will always return the same WebElement.

    Change your loop to something like this:

    for(WebElement el : driver.findElements(By.cssSelector("a.linkOffer"))) {
        String target =  el.getAttribute("href");        
        ..
    }