I need to find a specific city from a drop down list. I have tried using the xpath but the id number for the city keeps changing. The element from the website is below:

 <mat-option role="option" class="mat-option mat-focus-indicator mat-active ng-tns-c88-11 ng-star-inserted mat-selected" id="mat-option-14" tabindex="0" aria-disabled="false" style="" aria-selected="true"><!----><span class="mat-option-text"> Melbourne </span><!----><div mat-ripple="" class="mat-ripple mat-option-ripple"></div></mat-option>

My code:

WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH,'//*[@id="mat-option-14"]/span'))).click()

The code works only when the id is 14 but it can be any number. Can I select by the city name instead somehow? THanks

1 Answer 1


Yes, you can select the city by name using the text() function in XPath. Here's an example:

city_name = "Melbourne"

This will locate the span element that contains the city name and click on the corresponding mat-option element. Note that we're using an f-string to include the city_name variable in the XPath expression.

You can also locate the mat-option element based on the id attribute instead of the text. Here is an example code using find_element_by_css_selector method:

city_name = "mat-option-21"
option_element = driver.find_element_by_css_selector(f"mat-option[id^='mat-option-'][id$='-{city_name}']")

# Click on the option element to select the city

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.