4

I'm trying to select (if present) a month of the year in a dropdown list, where (month) can be any string from 'January' to 'December' (these are also the elements on the dropdown list)
But not every month is necessarily on the list.

Select(driver.find_element_by_id("selectMonth")).select_by_visible_text("%s" % (month))  

"selectMonth" is the id of the list, and the visible text is named according to the month. I have created a loop where I select each month from January to December, but I'm having problems when the month isn't on the list (NoSuchElementException).

How do I check if the month is on the dropdown list before trying to select it?

There's some good information about NoSuchElementException in this other post (Selenium "selenium.common.exceptions.NoSuchElementException" when using Chrome), but I couldn't use it to solve my problem. It's similar, but not the same.

Kobayashi
  • 119
  • 3
  • 10
  • Possible duplicate of [Selenium "selenium.common.exceptions.NoSuchElementException" when using Chrome](https://stackoverflow.com/questions/47993443/selenium-selenium-common-exceptions-nosuchelementexception-when-using-chrome) – undetected Selenium Feb 21 '18 at 16:59

2 Answers2

2

I think this should do the trick for what you're trying. I am adding the text of each month available in the dropdown to a list, that it will check against before trying to select the current month in the loop.

MonthSelect = Select(driver.find_element_by_id("selectMonth"))
DropDownOptions = []
# seems like you have the string of each month in a list/array already so I will refer to that
for option in MonthSelect.options: DropDownOptions.append(option.text)
for month in MonthList:
    if month in DropDownOptions:
        MonthSelect.select_by_visible_text("%s" % (month)) 

Edit:

As @Bob pointed out, you could also catch the Exception as so:

from selenium.common.exceptions import NoSuchElementException

try:
    Select(driver.find_element_by_id("selectMonth")).select_by_visible_text("%s" % (month))
except NoSuchElementException:
    pass

This way you can try every month, but just pass the months that are not present.

PixelEinstein
  • 1,713
  • 1
  • 8
  • 17
0

Instead of checking if the element is there you can also consider to assume it is easier to ask forgiveness than permission. In other words just try to select the thing, and catch the NoSuchElementException if it fails.

Bob
  • 614
  • 1
  • 7
  • 19