【问题标题】:How to open the second link in the adjacent tab? [duplicate]如何打开相邻选项卡中的第二个链接? [复制]
【发布时间】:2019-12-30 13:50:48
【问题描述】:

我一直在尝试许多功能来打开我最近打开的选项卡中的链接,但它不起作用。

带有注释的最小可重复示例,说明每行之后会发生什么(这是使用 Selenium webdriver,Java):

driver.get("https://twitter.com") //opens twitter in tab 1(intended)

((JavascriptExecutor)driver).executeScript("window.open('https://google.com')"); //opens new tab (tab 2) then opens google.com(intended)
((JavascriptExecutor)driver).executeScript("window.location.replace('https://facebook.com')"); //opens facebook.com in tab 1 (unintended)

我希望 Facebook 在标签 2 中打开。

【问题讨论】:

  • 嗯...window.location.replace 替换当前选项卡中的位置
  • 同样的结果,试过了。

标签: javascript selenium selenium-webdriver webdriverwait window-handles


【解决方案1】:

一旦您打开https://twitter.com 作为基本网址,然后在相邻的tab 中打开https://google.com。接下来在同一相邻的tab 中打开网址https://facebook.com,您必须为numberOfWindowsToBe(2) 诱导WebDriverWait,您可以使用以下解决方案:

  • 代码块:

    public class A_demo 
    {
        public static void main(String[] args) throws Exception 
        {
            System.setProperty("webdriver.chrome.driver", "C:\\Utility\\BrowserDrivers\\chromedriver.exe");
            ChromeOptions options = new ChromeOptions();
            options.addArguments("start-maximized");
            options.setExperimentalOption("excludeSwitches", Collections.singletonList("enable-automation"));
            options.setExperimentalOption("useAutomationExtension", false);
            WebDriver driver = new ChromeDriver(options);
            driver.get("https://twitter.com");
            String parent_window = driver.getWindowHandle();
            ((JavascriptExecutor) driver).executeScript("window.open('https://google.com');");
            new WebDriverWait(driver,5).until(ExpectedConditions.numberOfWindowsToBe(2));
            Set<String> allWindows = driver.getWindowHandles();
            for(String child_window:allWindows)
                if(!parent_window.equalsIgnoreCase(child_window))
                    driver.switchTo().window(child_window);
            driver.get("https://facebook.com");
            driver.quit();
        }
    }
    

【讨论】:

    猜你喜欢
    • 2018-07-19
    • 1970-01-01
    • 2022-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-17
    • 2017-11-28
    • 1970-01-01
    相关资源
    最近更新 更多