I'm currently using Selenium on Python and have got a question about it.
elements = driver.find_elements_by_css_selector("div.classname a")
for element in elements:
element.click()
driver.back()
Since coming back to the previous page using back() in this code, Selenium couldn't find elements anymore, even though I still need it.
If someone has got any clue, please help me out.
Many appreciate in advance
Selenium creates a whole new set of objects when you change pages -- whether you click a link, or go back a page. If clicking on the element in line 3 causes Selenium to load a new page, you're getting a StaleElementException on the second element test. So what you have to do is every time you execute driver.back(), you need to search for the element objects on the page as you do in the first line, and probably maintain at least a counter as to how far down the list of elements you've already clicked (assuming they navigate away from the page). Make sense?
You can store the elements in a list and work on them with a loop. For example:
elementList = driver.find_elements_by_css_selector("div.classname a")
for i in range(len(elementList)):
element = driver.find_elements_by_css_selector("div.classname a")[i]
element.click()
driver.back()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With