user2906074
user2906074

Reputation: 55

Looping through Links using Selenium

I'm trying to click through the loops of a given webpage. Once when it clicks, i need to grab the links again. I'm stuck where I have to pop the link from the stack. How would i keep gathering the other links and removing the duplicates?

public static void path(String url){
    WebDriver driver = new FirefoxDriver();
    driver.get(url);
    Deque<String> stack = new ArrayDeque<String>();
    boolean goal = true;
    while(!goal){
        for(WebElement links: driver.findElements(By.tagName("a"))){
            System.out.println(links.getAttribute("href"));
            stack.push(links.getAttribute("href"));
        }
        for(int i = 0; i < stack.size();i++){
            if(stack.)// remove duplicates ????????
            driver.get(stack.pop());
            i++;
        }

    }
}

HTML

<div id="menunav">
  <ul>
    <li><a href="index.php"><span>Home</span></a></li>
    <li><a href="chinese_menu.php"><span>Menu</span></a></li>
    <li><a href="chinese_food_catering.php"><span>Catering</span></a></li>
    <li><a href="restaurant_events.php"><span>Events</span></a></li>
    <li><a href="gallery.php"><span>Gallery</span></a></li>
    <li><a href="contact.php"><span>Contact</span></a></li>
  </ul>
</div>

Upvotes: 0

Views: 3200

Answers (1)

eugene.polschikov
eugene.polschikov

Reputation: 7339

imho, this piece of code provided above a bit bad-understanable code. I would suggest to operate on simple list:

List<WebElement> links = driver.findelements(By.cssSelector("a[href]"));

In this way you will get all the links with href attribute.

You can iterate through the list and operate on elements:

for(int  i =0; i< links.size(); i++) 
{
    links.get(i).click();
// and|or get text:       
//  links.get(i).getText();
}

to make it work for you (upon the problem description) you should wrap this with while and boolean condition flag:

bool condition=true;
while(condition)
{
   links = driver.findelements(By.cssSelector("a[href]"));
    for(int  i =0; i< links.size(); i++) 
    {
        links.get(i).click();
    // and|or get text:       
    //  links.get(i).getText();
     if(..analysis for condition goes here...) {
           condition=false;
              }
    }

}

Upvotes: 1

Related Questions