首页 > 解决方案 > 使用 selenium 在浏览器中打开多个 url

问题描述

我想使用以下命令在浏览器上打开多个 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)

请帮我修复它

标签: javaselenium

解决方案


将您的 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

推荐阅读