打开新选项卡时,Selenium会抛出IndexOutOfBoundsException

时间:2017-05-12 05:04:47

标签: java selenium selenium-chromedriver

Selenium Java程序在代码下执行时会抛出 IndexOutOfBoundsException 异常,以在Chrome中打开新标签页。

Java代码:

System.setProperty("webdriver.chrome.driver", "/Users/john/Desktop/chromedriver");
                    WebDriver driver = new ChromeDriver();
                    driver.manage().window().maximize();
                    String baseUrl = "http://google";
                    driver.get(baseUrl);
                    driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL + "t");

                    ArrayList<String> tabs = new ArrayList<String>(driver.getWindowHandles()); 
                    driver.switchTo().window(tabs.get(1)); // switches to  new tab
                    driver.get("https://www.facebook.com");

错误:

Starting ChromeDriver 2.29.461585 (0be2cd95f834e9ee7c46bcc7cf405b483f5ae83b) on port 48571
Only local connections are allowed.
May 12, 2017 12:54:14 AM org.openqa.selenium.remote.ProtocolHandshake createSession
INFO: Detected dialect: OSS
java.lang.IndexOutOfBoundsException: Index: 1, Size: 1
    at java.util.ArrayList.rangeCheck(ArrayList.java:653)
    at java.util.ArrayList.get(ArrayList.java:429)
    at test.SeleniumTest.main(SeleniumTest.java:31)

2 个答案:

答案 0 :(得分:2)

driver.switchTo().window(tabs.get(1));行中,你得到了这个例外。它正在发生,因为除了第一个窗口之外,你没有任何其他窗口打开。

答案 1 :(得分:1)

tabs的尺寸为1.您尝试访问位置1,而最高可能是0