如何解决Selenium点击第二个mat-radio-button时的索引越界问题?
问题分析与解决方案
错误原因
你的XPath定位的是<mat-radio-group>容器本身,所以findElements返回的列表仅包含1个元素(就是这个容器),调用list.get(1)自然触发索引越界异常。要点击第二个单选按钮,需要定位容器内的<mat-radio-button>子元素,而非容器本身。
正确解决方案
方案1:直接定位第二个单选按钮(通过索引)
利用XPath索引直接定位目标按钮(XPath索引从1开始):
WebElement secondRadio = driver.findElement(By.xpath("//mobileweb-accessorial-tasks-dialog//mobileweb-client-area//mat-radio-group[@id='searchType.toggle']//mat-radio-button[2]")); secondRadio.click();
方案2:先获取按钮列表再点击第二个
先定位radio group容器,再获取内部所有单选按钮,最后点击列表中索引为1的元素(Java列表索引从0开始):
WebElement radioGroup = driver.findElement(By.xpath("//mobileweb-accessorial-tasks-dialog//mobileweb-client-area//mat-radio-group[@id='searchType.toggle']")); List<WebElement> radioButtons = radioGroup.findElements(By.tagName("mat-radio-button")); radioButtons.get(1).click();
方案3:通过文本/属性定位(更稳定)
如果按钮文本或属性固定,可直接通过这些特征定位,避免依赖索引变化:
- 通过按钮文本"Work Order"定位:
WebElement workOrderRadio = driver.findElement(By.xpath("//mobileweb-accessorial-tasks-dialog//mobileweb-client-area//mat-radio-group[@id='searchType.toggle']//span[text()='Work Order']/ancestor::mat-radio-button")); workOrderRadio.click();
- 通过input的
value="1"属性定位:
WebElement workOrderRadio = driver.findElement(By.xpath("//mobileweb-accessorial-tasks-dialog//mobileweb-client-area//mat-radio-group[@id='searchType.toggle']//input[@value='1']/ancestor::mat-radio-button")); workOrderRadio.click();
可选:添加显式等待避免加载问题
如果页面存在延迟,可通过显式等待确保元素可点击:
WebDriverWait wait = new WebDriverWait(driver, 10); WebElement secondRadio = wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//mobileweb-accessorial-tasks-dialog//mobileweb-client-area//mat-radio-group[@id='searchType.toggle']//mat-radio-button[2]"))); secondRadio.click();
内容的提问来源于stack exchange,提问作者Peter Penzov
相关产品推荐
相关产品推荐

