Reputation: 21
I'm using Selenium WebDriver I need to perform and action(click) on the first account item, do something, then come back and repeat the process again on the next item. It can potentially be up-to 90 account items so I'm trying to avoid hard coding all 90. any idea how to perhaps loop through the account-list?
<ul class="account-list">
<li class="account-item">one item</li>
<li class="account-item">two items</li>
<li class="account-item">three items</li>
</ul>
Upvotes: 1
Views: 2502
Reputation: 4194
You can't iterate over a list of elements in Selenium because their object references will become invalid when the DOM changes (StaleElement exception), but you can do it by index number so long as the size of your list doesn't change
elements = @driver.find_elements(css: ".account-item>a")
elements.size.times do |i|
@driver.find_element(css: ".account-list > li:nth-child(#{i})>a").click
# Do something
@driver.navigate.back
end
Upvotes: 1
Reputation: 7401
You can do it by getting the all elements by their css
then iterate throutght the elements as following:
elems = driver.find_elements(:css => ".account-list > li")
url = driver.current_url
for i in 0..elems.size
# wait until the element loads
wait.until { driver.find_element(:css => ".account-list > li:nth-child(#{i})")}
elems[i].click()
#do your tests
# ...
# go back
driver.navigate.to url
end
Upvotes: 0