如何关闭两个标签并使用不同的URL打开一个新标签

时间:2019-12-02 04:01:06

标签: java selenium testing selenium-webdriver

我在质量检查中有一个测试用例,其中访客单击链接,然后将打开一个新标签。但是此新选项卡默认为Prod,因此我不想继续在prod中使用测试用例,而是希望此选项卡关闭并导航到其他URL(指向质量检查的URL)。如何使用Selenium Web驱动程序实现此目的?

1 个答案:

答案 0 :(得分:0)

除了单击链接外,您还可以保存其href属性,并让驱动程序加载所需的URL。或者,您可以在标签之间切换。以下代码将为您提供帮助。

package links;

import java.util.ArrayList;

import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

public class Links {

    public static void main(String[] args) {

        // init driver
        String chromeDriverPath = "C:\\Users\\pavel.burgr\\Desktop\\webdrivers\\chromedriver.exe";
        System.setProperty("webdriver.chrome.driver", chromeDriverPath);
        ChromeOptions options = new ChromeOptions();
        WebDriver driver = new ChromeDriver(options);
        driver.manage().window().maximize();

        // get EN page
        driver.get("https://en.wikipedia.org/wiki/Hyperlink");
        waitSec(driver, 10).until(ExpectedConditions.elementToBeClickable(By.id("p-logo")));
        WebElement hyperlinked = driver.findElement(By.xpath("//a[contains(@href,'/wiki/Hyperlinked')]"));

        // get the href attribute of webelement 'Hyperlinked'
        String href = hyperlinked.getAttribute("href");

        // change the href
        String alteredHref = href.replace(".en", ".cs");

        // open new Tab
        openAndGoToNewTab(driver);

        // load page with altered url (czech version of the same page)
        driver.get(alteredHref);
        waitSec(driver, 10).until(ExpectedConditions.elementToBeClickable(By.id("p-logo")));
    }

    // custom wait method
    public static WebDriverWait waitSec(WebDriver driver, int sec) {
        return new WebDriverWait(driver, sec);
    }


    // opens new tab and switch to it
    public static void openAndGoToNewTab(WebDriver driver) {
        JavascriptExecutor js = (JavascriptExecutor) driver;
        js.executeScript("window.open()");
        ArrayList<String> tabs = new ArrayList<String>(driver.getWindowHandles());
        driver.switchTo().window(tabs.get(tabs.size() - 1));
    }

    // close current tab
    public static void closeTab(WebDriver driver) {
        JavascriptExecutor js = (JavascriptExecutor) driver;
        js.executeScript("window.close()");
    }

    // switch to tab by index
    public static void swotchToTab(WebDriver driver, int tabIndex) {
        ArrayList<String> tabs = new ArrayList<String>(driver.getWindowHandles());
        driver.switchTo().window(tabs.get(tabIndex));
    }
}