如何基于mat-option-text中的城市名称定位并点击下拉选项(Selenium)
解决方案
核心思路:通过城市文本定位元素
由于mat-option的id是动态生成的,改用文本匹配的方式定位,完全不受id变化影响。
方法1:直接匹配span的文本(推荐)
利用XPath的normalize-space()处理文本前后的空白字符(比如元素里的Melbourne带前后空格),确保精准匹配:
from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC # 定位并点击目标城市 WebDriverWait(driver, 20).until(EC.element_to_be_clickable( (By.XPATH, '//mat-option/span[normalize-space(text())="Melbourne"]') )).click()
方法2:匹配父元素mat-option
也可以直接定位mat-option元素,通过其子元素的文本判断:
WebDriverWait(driver, 20).until(EC.element_to_be_clickable( (By.XPATH, '//mat-option[normalize-space(span/text())="Melbourne"]') )).click()
复用性优化
如果需要定位多个城市,可将城市名称设为变量:
target_city = "Melbourne" WebDriverWait(driver, 20).until(EC.element_to_be_clickable( (By.XPATH, f'//mat-option/span[normalize-space(text())="{target_city}"]') )).click()
内容的提问来源于stack exchange,提问作者user2061944
相关产品推荐
相关产品推荐

