Valip
Valip

Reputation: 4610

How to use selenium webdriver to click on links

How can I use selenium webdriver to get all links from the page that have the property a[href*=/simulation/form/] and then open and close each of them?

I tried the following code but it returns TypeError: link.click is not a function

var simLinks = driver.findElements(By.css('a[href*=/simulation/form/]'));

for(var link in simLinks){
  link.click();
  driver.wait(30000);
  driver.back();
}

If I do console.log(simLinks.length) it returns undefined

Instead, it works perfect if I try to open a single link of that type:

var simLinks = driver.findElement(By.css('a[href*=/simulation/form/]')).click();

Upvotes: 2

Views: 170

Answers (2)

Lima Mairante
Lima Mairante

Reputation: 84

Use the util.inspect() function to inspect objects:

const util = require('util');
...
console.log(util.inspect(simLinks));

Once you do that, you will see that simLinks is a ManagedPromise, so you need to change your code as follows to make it work:

driver.findElements(By.css('a[href*="/simulation/form/"]')).then(function (simLinks) {
  for (let link of simLinks) {
    link.click();
    driver.wait(until.urlContains('/simulation/form/', 30000));
    driver.navigate().back();
  }
});

The problem with that, however, is that only the first click works, but once you navigate back there is a legitimate StaleElementReferenceError - the page has indeed changed and the next element in the loop is no longer attached to the visible page. Therefore, a better strategy would be to collect the link addresses instead and use these with driver.navigate().to(link):

driver.findElements(By.css('a[href*="/simulation/form/"]')).then(function (simLinks) {
  var hrefs = simLinks.map(link => link.getAttribute('href'));
  for (let link of hrefs) {
    driver.navigate().to(link);
    driver.wait(until.urlContains('/simulation/form/', 30000));
    driver.navigate().back();
  }
});

Upvotes: 2

Bill Hileman
Bill Hileman

Reputation: 2838

I believe you should be using:

console.log(simLinks.size())

I don't know if the () is required in javascript - it is in java.

Upvotes: 0

Related Questions