如何遍历mat-radio-group父节点并点击指定单选按钮,不受ID影响
实现方案
你可以通过外层固定的id="searchType"作为定位锚点,先找到父容器再匹配子单选按钮,完全不需要依赖内部动态生成的mat-radio-*类随机ID。
原生JavaScript实现
按索引点击(选项顺序固定场景)
- 点击第一个选项(Shipment):
// 定位稳定父容器 const radioGroup = document.querySelector('#searchType mat-radio-group'); // 获取所有单选按钮列表 const radioList = radioGroup.querySelectorAll('mat-radio-button'); // 索引从0开始计数,点击第一个 radioList[0].click();
- 点击第二个选项(Work Order):
const radioGroup = document.querySelector('#searchType mat-radio-group'); const radioList = radioGroup.querySelectorAll('mat-radio-button'); radioList[1].click();
按文本匹配点击(选项顺序可能变动场景)
这种方式稳定性更高,不会因为选项顺序调整失效:
const radioGroup = document.querySelector('#searchType mat-radio-group'); const radioList = radioGroup.querySelectorAll('mat-radio-button'); // 替换targetText的值即可点击对应选项 const targetText = 'Work Order'; for (const btn of radioList) { const label = btn.querySelector('.mat-radio-label-content').textContent.trim(); if (label === targetText) { btn.click(); break; } }
自动化测试场景(以Selenium Python为例)
按索引点击:
from selenium.webdriver.common.by import By # 定位父容器 radio_group = driver.find_element(By.CSS_SELECTOR, '#searchType mat-radio-group') # 点击第一个选项 radio_group.find_elements(By.CSS_SELECTOR, 'mat-radio-button')[0].click()
按文本匹配点击:
from selenium.webdriver.common.by import By driver.find_element( By.XPATH, '//div[@id="searchType"]//mat-radio-button[contains(.,"Work Order")]' ).click()
内容的提问来源于stack exchange,提问作者Peter Penzov
相关产品推荐
相关产品推荐

