0

I need to find and click on a specific city from a drop down list using selenium. I have tried using the xpath but the id number for the city keeps changing with every refresh of the page. 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 currently uses xpath:

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 so when it changes the code breaks. Also there are multiple cities with different ids. Can I find and click by the city name instead somehow? Thanks

user2061944
  • 319
  • 1
  • 3
  • 11

2 Answers2

1

Try by searching for city name directly in the XPath. Try the below XPath expression:

//span[contains(text(),'Melbourne')]

If it locates the element, you can change the city name accordingly as per your choice.

Shawn
  • 4,064
  • 2
  • 11
  • 23
1

You can use class name for selecting city.

   driver.find_element(By.CSS_SELECTOR,'.mat-option.mat-focus-indicator.mat- 
   active.ng-tns-c88-11.ng-star-inserted.mat-selected')

For more information you can see this webdriver-classname-with-space