eightb4ll
eightb4ll

Reputation: 13

Perform a repeated click on an element in selenium

I've located the elements I need in a webpage, and called them each something appropriate. Is there a way to just call the element by name later in the test script and click it, without having to locate the element again?

Tried splitting the find_element_by/.click() into two separate lines, so I know it can reference the name I've assigned to the element.

costs = browser.find_element_by_css_selector('g:nth-child(2) > g > circle')
costs.click()

revenue = browser.find_element_by_css_selector('#chart-div-2 g:nth-child(1) > rect')
revenue.click()

(then after these steps and a few similar, I've tried adding in....)

costs.click()
revenue.click()

Message:

'stale element reference: element is not attached to the page document', but I've not navigated away from the page.

What am I missing

Upvotes: 1

Views: 812

Answers (1)

Moshe Slavin
Moshe Slavin

Reputation: 5204

You just need to refer to them again since the element is stale.

So in your case:

costs = browser.find_element_by_css_selector('g:nth-child(2) > g > circle')
costs.click()
revenue = browser.find_element_by_css_selector('#chart-div-2 g:nth-child(1) > rect')
revenue.click()

# DO SOME STUFF

costs = browser.find_element_by_css_selector('g:nth-child(2) > g > circle')
costs.click()
revenue = browser.find_element_by_css_selector('#chart-div-2 g:nth-child(1) > rect')
revenue.click()

Read more about Stale Element Reference Exception.

Upvotes: 1

Related Questions