ajaay kannan Vr
ajaay kannan Vr

Reputation: 45

How to traverse each dropdown list using selenium WebDriver python

I have the web result with the html tags as below, I need to loop each value and get the results from the table

<div class = "divList">
<select class="form selectList">
<option value="3710">Thu, 04 Nov 2021</option>
<option value="3709">Mon, 01 Nov 2021</option>
<option value="3708">Mon, 01 Nov 2021</option>
....
</select>
</div>

dropdownlist = driver.find_element_by_class_name('divList')
valueslist = (dropdownlist.text).splitlines()
print(valueslist)
sel = Select(driver.find_element_by_xpath("//select[@class='form selectList']"))
for value in valueslist:
   print(value)
   sel.select_by_visible_text(value)
   print('Processing - ', value)
   time.sleep(3)

Getting the below error while changing the value after 2 iteration

Thu, 04 Nov 2021
Processing -  Thu, 04 Nov 2021
Mon, 01 Nov 2021
Processing -  Mon, 01 Nov 2021
Thu, 28 Oct 2021

selenium.common.exceptions.StaleElementReferenceException: Message: stale element reference: element is not attached to the page document

Upvotes: 1

Views: 326

Answers (1)

Frenchy
Frenchy

Reputation: 17037

try this:

dropdownlist = driver.find_element_by_class_name('divList')
valueslist = (dropdownlist.text).splitlines()
print(valueslist)
sel = Select(driver.find_element_by_xpath("//select[@class='form selectList']"))

for value in valueslist:
    sel = Select(driver.find_element_by_xpath("//select[@class='form selectList']"))
    sel.select_by_visible_text(value)
    print('Processing - ', value)
    time.sleep(3)

you could simplify if you want by:

sel = Select(driver.find_element_by_xpath("//select[@class='form selectList']"))
nbritems = len(sel.options)
for i in range(0, nbritems):
    sel = Select(driver.find_element_by_xpath("//select[@class='form selectList']"))
    txt = sel.options[i].text
    sel.select_by_visible_text(txt)
    print('Processing - ', txt)
    time.sleep(3)

selenium.common.exceptions.StaleElementReferenceException: Message: stale element reference: element is not attached to the page document

The literal meaning is about , The referenced element is out of date , No longer attached to the current page . Usually , This is because the page has been refreshed or skipped , The solution is , Reuse findElement or findElements Method to locate the element .

Upvotes: 2

Related Questions