簡體   English   中英

如何關閉兩個標簽並使用不同的網址打開一個新標簽

[英]How to close two tabs and open a new tab with different url

我在 QA 中有一個測試用例,來賓單擊鏈接並打開一個新選項卡。 但是這個新選項卡默認為 Prod,所以我不想在 prod 中繼續我的測試用例,我希望這個選項卡關閉並導航到不同的 url(指向 QA 的那個)。 我如何使用 selenium web 驅動程序實現這個?

您可以保存它的 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));
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM