1

Site has top menu with 6 links. I can get list of this links like this:

links = browser.find_elements_by_css_selector(MENU_LINKS_CSS_SELECTOR)

After this I need to click this links one by one. If I do it like this:

for link in links:
    link.click()

I get the following error: selenium.common.exceptions.StaleElementReferenceException: Message: u'Element not found in the cache - perhaps the page has changed since it was looked up'. As I understand, this error raises beacause of connection betweeb WebElement instances and DOM of the web-page is broken after reloading the page (clicking on link).

Here I should notice that top menu is the same on all pages.

So, what I do wrong? How to fix this? TIA!

1
  • 1
    So you're aware the exception you receiving is likely caused by the page reloading as links are clicked. As such the saved 'selenium' reference to the link next in your list will no longer exist. As per Svineet's answer, you will need to gather the list of links each time you wish to click the next one - 'refreshing' the selenium references to each link. Commented Jul 22, 2013 at 9:58

2 Answers 2

5

I don't know much Selenium but you should select the links again -

for i in range(0,6):
    links = browser.find_elements_by_css_selector(MENU_LINKS_CSS_SELECTOR)
    links[i].click()
Sign up to request clarification or add additional context in comments.

Comments

0

Another way to do it would be to do about the same thing, but use a slightly different approach...

for i in range(len(browser.find_elements_by_css_selector)):
    link = browser.find_element_by_css_selector('ul > li:nth-child({})'.format(i + 1))
    link.click()

This way is slightly more optimized as it doesn't get the full array of elements every time the page reloads

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.