Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Selenium keeping elements after changed browser

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

like image 648
Joon Avatar asked Nov 15 '25 22:11

Joon


2 Answers

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?

like image 172
Ron Norris Avatar answered Nov 18 '25 10:11

Ron Norris


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()
like image 27
Amit Verma Avatar answered Nov 18 '25 12:11

Amit Verma



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!