java - 在新标签页中打开 Google 链接

标签 java selenium

我想在新标签页中打开 Google 搜索结果。我尝试了这段代码:

WebDriver driver = new ChromeDriver();
        driver.get("http://www.google.com/xhtml");
        Thread.sleep(5000);
        WebElement searchBox = driver.findElement(By.name("q"));
        searchBox.sendKeys("ChromeDriver");
        searchBox.submit();

        System.out.println("Current Url: " + driver.getCurrentUrl());

        WebDriverWait wait = new WebDriverWait(driver, 10);
        wait.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector("h3.r a")));

        List<WebElement> results = driver.findElements(By.xpath("//h3[@class='r']/a"));

        for (int i = 0; i < results.size(); i++)
        {
            String selectLinkOpeninNewTab = Keys.chord(Keys.CONTROL,Keys.RETURN);
            driver.findElement(By.xpath("//h3[@class='r']/a")).sendKeys(selectLinkOpeninNewTab);

            System.out.println("Google result " + results.get(i).getText());
        }

到目前为止,代码会打开空选项卡并打印搜索结果的名称。如何打开搜索结果中的链接?

最佳答案

只需更改循环内的以下行:-

driver.findElement(By.xpath("//h3[@class='r']/a")).sendKeys(selectLinkOpeninNew‌​Tab);

results.get(i).sendKeys(selectLinkOpeninNewTab);

它正在工作......:)

关于java - 在新标签页中打开 Google 链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38073545/

相关文章:

angularjs - Protractor 和 appium - 无法读取未定义的属性

java - 当框架是Hybrid并且测试用例由Selenium中的excel驱动时,如何使用TestNG注释?

java - 使用selenium java获取li列表

java - 等待页面元素(xpath)在 Selenium Webdriver 中显示的最有效方法是什么?

java - 嵌入实体的自动ID

java - 防止在 Java 中创建/启动线程

java - getScreenshotAs 方法在哪里定义?

java - Secure iNet Factory 和 Apache httpclient,哪个更强大?

java - 在嵌套类 JAVA 中使用变量

java - 我的蛇不会开始移动