Skip to content Skip to sidebar Skip to footer

How Do I Click All Elements In Selenium Webdriver?

Updated I'm using: Selenium 2.53.1 Firefox and IE11 I've been trying to click on all elements with the same selector, for example, I want to click on all the ones with the title

Solution 1:

You need to find them one by one, on page reload your objects will be lost and you will get stale element exception.

1) find all links 2) save an attribute/attributes in a list/array that can help you identify each link 3) create a loop where for each attribute you are searching for the element and click it

Solution 2:

Moving my comment to an answer...

  1. The first issue is that your code attempts are clicking a collection rather than an individual element. There are several ways to do this, one of which is doing a for loop and accessing the individual elements inside the loop, e.g. all_tests[i].click();.
  2. The second issue with stale elements is because the DOM is being changed either through refreshing the page or navigating to a new page. If the issue is that clicking is causing navigation, you can loop through all the A tags and store the hrefs in a string array. Then you can loop through that string array and navigate to each stored href, etc.

    Another way to handle this is to scrape the page using the index rather than storing the collection outside the loop. A simple example of this is

    This is Java/pseudocode that you will have to translate into whatever language you are using but the concept should work.

    for (int i = 0; i < driver.findElements(locator).length; i++)
    {
        // scrapes the page each iteration to avoid the stale element exception
        driver.findElements(locator)[i].click();
        // do stuff and get back to the original page, if navigated
    }
    

Solution 3:

I think first print the all_tests, check the output and the changes in the for loop could work

for element in all_tests: element.click()

And to handle StaleElementReferenceError, can check here: StaleElementReferenceException on Python Selenium

NOTE: Not Tested but handled the same concern.

Post a Comment for "How Do I Click All Elements In Selenium Webdriver?"