1

Here's the HTML of what looks to be a dropdown list:

<div id="Form-PlaceList-boundlist" class="x-boundlist x-boundlist
 floating x-layer x-boundlist-default x-border-box x-boundlist-above">
<div id="Form-PlaceList-boundlist-listEl" class="x-boundlist-list-ct
 x-unselectable" role="presentation">
<ul class="x-list-plain">
<li class="x-boundlist-item x-boundlist-item-over x-boundlist-selected"
 role="option" unselectable="on"></li>
<li class="x-boundlist-item" role="option" unselectable="on">Alabama</li>
<li class="x-boundlist-item" role="option" unselectable="on">Alaska</li>
<li class="x-boundlist-item" role="option" unselectable="on">Atlantis</li>

Using Selenium with Python 2.7, I've trying to select one of the list/option elements. I can get the desired element by using

driver.find_element_by_xpath("//div[@id='Form-PlaceList-boundlist-ListEl']/ul/li[62]")

...except the list order changes from time to time, and row number #62 isn't sometimes the right element.

Can you select this element based on "Wyoming" rather than the index number?

I also tried getting it with sending a Javascript command to the Selenium driver with driver.execute_script. I tried:

driver.execute_script("document.getElementByID('Form-PlaceList-boundlist-listEl').setAttribute('value','Wyoming')")

but this gives Cannot read property 'setAttribute' of null.

Suzanne
  • 582
  • 2
  • 11
  • 31

1 Answers1

1

You can locate the element based on it's text using an XPath locator:

dropdown = driver.find_element_by_css_selector("#Form-PlaceList-boundlist #orm-PlaceList-boundlist-listEl ul")

wyoming = dropdown.find_element_by_xpath(".//li[. = 'Wyoming']")
wyoming.click()

The dot in the expression in this case refers to the current element's text.

Note: don't forget to open up the dropdown before clicking an option inside it.

Community
  • 1
  • 1
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195