如何使用Selenium选择ID动态变化的单选按钮组的第一个选项
实现方案
你当前的定位代码存在小问题:mat-radio-group[data-cy='tv-select']匹配的是整个单选按钮组(仅1个元素),而不是组内的单选按钮列表,不需要用List<WebElement>接收。
你可以通过固定属性定位单选组后,按顺序匹配第一个选项,完全不受动态ID、动态内容的影响,以下是两种可直接使用的实现方式:
方案1:一步定位直接操作(推荐)
用CSS伪类:first-of-type直接定位到组内第一个单选按钮,Angular Material组件直接点击mat-radio-button元素即可触发选中:
import org.openqa.selenium.support.ui.WebDriverWait; import org.openqa.selenium.support.ui.ExpectedConditions; import java.time.Duration; // 定位单选组内第一个单选按钮 @FindBy(css = "mat-radio-group[data-cy='tv-select'] mat-radio-button:first-of-type") private WebElement firstTvRadioBtn; // 操作代码(调用前确保页面已加载完成) // 加显式等待避免元素未加载报错 WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10)); wait.until(ExpectedConditions.elementToBeClickable(firstTvRadioBtn)).click();
如果点击mat-radio-button不生效,也可以定位原生input元素用JS执行点击,规避元素可见性限制:
// 定位第一个单选按钮的原生input @FindBy(css = "mat-radio-group[data-cy='tv-select'] mat-radio-button:first-of-type input[type='radio']") private WebElement firstTvRadioInput; // JS点击代码 JavascriptExecutor js = (JavascriptExecutor) driver; js.executeScript("arguments[0].click();", firstTvRadioInput);
方案2:先定位组再查找子元素(适合批量操作场景)
如果后续需要操作组内多个单选按钮,可以先定位整个组,再按需查找子元素:
// 定位整个单选按钮组 @FindBy(css = "mat-radio-group[data-cy='tv-select']") private WebElement tvRadioGroup; // 操作代码 WebElement firstBtn = tvRadioGroup.findElement(By.cssSelector("mat-radio-button:first-of-type")); new WebDriverWait(driver, Duration.ofSeconds(10)) .until(ExpectedConditions.elementToBeClickable(firstBtn)) .click();
内容的提问来源于stack exchange,提问作者diher81
相关产品推荐
相关产品推荐

