How to Fetch All Links and Click Those Links One by One Using Selenium Webdriver

How to fetch all links and click those links one by one using Selenium WebDriver

There is no such a good idea to have following scenario :

for (WebElement element : webDriver.findElements(locator.getBy())){
element.click();
}

Why? Because there is no guarantee that the element.click(); will have no effect on other found elements, so the DOM may be changed, so hence the StaleElementReferenceException.

It is better to use the following scenario :

int numberOfElementsFound = getNumberOfElementsFound(locator);
for (int pos = 0; pos < numberOfElementsFound; pos++) {
getElementWithIndex(locator, pos).click();
}

This is better because you will always take the WebElement refreshed, even the previous click had some effects on it.

EDIT : Example added

  public int getNumberOfElementsFound(By by) {
return webDriver.findElements(by).size();
}

public WebElement getElementWithIndex(By by, int pos) {
return webDriver.findElements(by).get(pos);
}

Hope to be enough.

fetch all links under/in a specific class-selenium webdriver (java)

Actually you are using incorrect xpath to locating pret,summer sale,accessories, bt lawn'16, sale, lookbook, links try as below :-

List<WebElement> allLinks = driver.findElements(By.cssSelector("a.level0"));
Random random = new Random();
WebElement randomLink = allLinks.get(random.nextInt(allLinks.size()));
randomLink.click();

WebDriver script for clicking all links except one with particular name not working

The issue you're encountering is that when you click a link, you're leaving the page. This makes the collection of elements in your List "stale".

This is an approach that should work for you. Of course, this assumes that all of the links have different link text.

List<WebElement> allLinks = driver.findElements(By.tagName("a"));
String ofLinks[] = new String[allLinks.size()];
for (int i = 0; i < allLinks.size(); i++){
if(!allLinks.get(i).getText().equals("SUPPORT")){
ofLinks[i] = allLinks.get(i).getText();
}
}

for (int i = 0; i < allLinks.size(); i++){
if (ofLinks[i] != null){
driver.findElement(By.LinkText(ofLinks[i])).click();
}
driver.findElement(By.linkText("Home")).click();
}


Related Topics



Leave a reply



Submit