在浏览器中使用硒打开多个URL

时间:2018-06-21 05:03:57

标签: java selenium

我想使用以下命令在浏览器中打开多个URL

public static void main(String[] args) {
    System.setProperty("webdriver.chrome.driver", "E:\\Java\\Library\\seleniumhq\\chromedriver_win32_2.40.exe");
    WebDriver webDriver = new ChromeDriver();

    openNewTab(webDriver, "http://dantri.com.vn/phap-luat.htm", 1);
    openNewTab(webDriver, "http://dantri.com.vn/xa-hoi.htm", 2);
    openNewTab(webDriver, "http://dantri.com.vn/the-gioi.htm", 3);
    openNewTab(webDriver, "http://dantri.com.vn/the-thao.htm", 4);
    openNewTab(webDriver, "http://dantri.com.vn/giao-duc-khuyen-hoc.htm", 5);

}

public void openNewTab(WebDriver webDriver, String url, int position) {
    ((JavascriptExecutor) webDriver).executeScript("window.open()");

    ArrayList<String>  tabs = new ArrayList<>(webDriver.getWindowHandles());
    System.out.println("tabs : " + tabs.size() + " >position: " + position + " >\t" + url);
    webDriver.switchTo().window(tabs.get(position));

    webDriver.get(url);
}

尽管已打开浏览器选项卡,但tabs.size()保持不变,从而导致错误。

tabs : 2 >position: 1 > http://dantri.com.vn/phap-luat.htm
tabs : 2 >position: 2 > http://dantri.com.vn/xa-hoi.htm
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 2, Size: 2
    at java.util.ArrayList.rangeCheck(ArrayList.java:657)
    at java.util.ArrayList.get(ArrayList.java:433)
    at test.test.NewClass.openNewTab(NewClass.java:37)
    at test.test.NewClass.<init>(NewClass.java:25)
    at test.test.NewClass.main(NewClass.java:43)

请帮助我修复它

1 个答案:

答案 0 :(得分:2)

将openNewTab方法更改为静态方法。我没有得到异常,也没有得到预期的响应。

修改后的代码:

public class MultiTab {

    public static void main(String args[]){
        System.setProperty("webdriver.chrome.driver", "drivers/chromedriver.exe");
        WebDriver webDriver =new ChromeDriver();
        openNewTab(webDriver, "http://dantri.com.vn/phap-luat.htm", 1);
        openNewTab(webDriver, "http://dantri.com.vn/xa-hoi.htm", 2);
        openNewTab(webDriver, "http://dantri.com.vn/the-gioi.htm", 3);
        openNewTab(webDriver, "http://dantri.com.vn/the-thao.htm", 4);
        openNewTab(webDriver, "http://dantri.com.vn/giao-duc-khuyen-hoc.htm", 5);
    }

    public static void openNewTab(WebDriver webDriver, String url, int position) {
        ((JavascriptExecutor) webDriver).executeScript("window.open()");
        ArrayList<String> tabs = new ArrayList<>(webDriver.getWindowHandles());
        System.out.println("tabs : " + tabs.size() + " >position: " + position + " >\t" + url);
        webDriver.switchTo().window(tabs.get(position));
        webDriver.get(url);
    }
}

输出:

tabs : 2 >position: 1 > http://dantri.com.vn/phap-luat.htm
tabs : 3 >position: 2 > http://dantri.com.vn/xa-hoi.htm
tabs : 4 >position: 3 > http://dantri.com.vn/the-gioi.htm
tabs : 5 >position: 4 > http://dantri.com.vn/the-thao.htm
tabs : 6 >position: 5 > http://dantri.com.vn/giao-duc-khuyen-hoc.htm