selenium错误为“线程中的异常”main“java.lang.IndexOutOfBoundsException:索引:1,大小:0”,代码为:
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
public class Web_driver {
public static void main(String[] args) {
WebDriver driver = new FirefoxDriver();
driver.get("http://www.quackit.com/html/codes/html_radio_button.cfm");
List<WebElement> radio_button = driver.findElements(By.name("Preferred_color"));
System.out.println(radio_button.get(1).getAttribute("value"));
执行上述代码后,错误显示为“线程中的异常”main
java.lang.IndexOutOfBoundsException: Index: 1, Size: 0
at java.util.ArrayList.rangeCheck(Unknown Source)
at java.util.ArrayList.get(Unknown Source)
at Web_driver.main(Web_driver.java:16)
# 1 楼答案
它在网页上找不到具有给定名称的元素,单选按钮列表为空。尝试获取第一个元素会产生IndexOutOfBoundsException。顺便检查一下。命名以查看如何查找元素。此外,在Java中,单选按钮应该是radioButton
# 2 楼答案
您的代码找不到名为“Preferred_color”的单选按钮,因此返回的列表
radio_button
似乎为空。因此,当你试图调用radio_button.get(1)
时,这会导致NullPointerException
添加此空检查以避免异常: