web-dev-qa-db-fra.com

Changer d'onglet avec Selenium WebDriver avec Java

Utilisation de Selenium WebDriver avec Java ... Je tente d’automatiser une fonctionnalité dans laquelle je dois ouvrir un nouvel onglet, y effectuer certaines opérations et revenir à l’onglet précédent (Parent) . Et il est étrange que les deux onglets aient le même descripteur de fenêtre, ce qui ne permet pas de basculer entre les onglets.

Cependant, lorsque j'essaie avec différentes fenêtres Firefox, cela fonctionne, mais pour Tab, cela ne fonctionne pas.

Aidez-moi, s'il vous plaît, comment puis-je changer d'onglet . OU comment puis-je changer d'onglet sans utiliser le handle de fenêtre, celui-ci étant identique pour les deux onglets.

(J'ai observé que lorsque vous ouvrez différents onglets dans la même fenêtre, le handle de fenêtre reste le même)

51
Umesh Kumar
    psdbComponent.clickDocumentLink();
    ArrayList<String> tabs2 = new ArrayList<String> (driver.getWindowHandles());
    driver.switchTo().window(tabs2.get(1));
    driver.close();
    driver.switchTo().window(tabs2.get(0));

Ce code a parfaitement fonctionné pour moi. Essaye le. Vous devez toujours basculer votre pilote sur un nouvel onglet avant de faire quelque chose sur un nouvel onglet.

79
Sireesha Middela

Il s’agit d’une solution simple pour ouvrir un nouvel onglet, y changer l’attention, la fermer et revenir à l’ancien/original

@Test
public void testTabs() {
    driver.get("https://business.Twitter.com/start-advertising");
    assertStartAdvertising();

    // considering that there is only one tab opened in that point.
    String oldTab = driver.getWindowHandle();
    driver.findElement(By.linkText("Twitter Advertising Blog")).click();
    ArrayList<String> newTab = new ArrayList<String>(driver.getWindowHandles());
    newTab.remove(oldTab);
    // change focus to new tab
    driver.switchTo().window(newTab.get(0));
    assertAdvertisingBlog();

    // Do what you want here, you are in the new tab

    driver.close();
    // change focus back to old tab
    driver.switchTo().window(oldTab);
    assertStartAdvertising();

    // Do what you want here, you are in the old tab
}

private void assertStartAdvertising() {
    assertEquals("Start Advertising | Twitter for Business", driver.getTitle());
}

private void assertAdvertisingBlog() {
    assertEquals("Twitter Advertising", driver.getTitle());
}
19
Jordan Silva

Il existe une différence entre le pilote Web et différentes fenêtres et sa gestion des différents onglets.

Cas 1:
S'il existe plusieurs fenêtres, le code suivant peut vous aider:

//Get the current window handle
String windowHandle = driver.getWindowHandle();

//Get the list of window handles
ArrayList tabs = new ArrayList (driver.getWindowHandles());
System.out.println(tabs.size());
//Use the list of window handles to switch between windows
driver.switchTo().window(tabs.get(0));

//Switch back to original window
driver.switchTo().window(mainWindowHandle);


Cas 2:
S'il y a plusieurs onglets dans la même fenêtre, il n'y a qu'un seul handle de fenêtre. Par conséquent, le passage d'une fenêtre à l'autre conserve le contrôle dans le même onglet.
Dans ce cas, il est plus utile d’utiliser Ctrl +\t (Ctrl + Tab) pour passer d’un onglet à l’autre.

//Open a new tab using Ctrl + t
driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL +"t");
//Switch between tabs using Ctrl + \t
driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL +"\t");

Vous trouverez un exemple de code détaillé ici:
http://design-interviews.blogspot.com/2014/11/switching-between-tabs-in-same-browser-window.html

11
Sourabh

Solution de contournement

Assumption: en cliquant sur quelque chose sur votre page web conduit à ouvrir un nouvel onglet.

Utilisez la logique ci-dessous pour passer au deuxième onglet.

new Actions(driver).sendKeys(driver.findElement(By.tagName("html")), Keys.CONTROL).sendKeys(driver.findElement(By.tagName("html")),Keys.NUMPAD2).build().perform();

De la même manière, vous pouvez revenir au premier onglet.

new Actions(driver).sendKeys(driver.findElement(By.tagName("html")), Keys.CONTROL).sendKeys(driver.findElement(By.tagName("html")),Keys.NUMPAD1).build().perform();
7
Santoshsarma
String selectLinkOpeninNewTab = Keys.chord(Keys.CONTROL, Keys.RETURN);
    WebElement e = driver.findElement(By
            .xpath("html/body/header/div/div[1]/nav/a"));
e.sendKeys(selectLinkOpeninNewTab);//to open the link in a current page in to the browsers new tab

    e.sendKeys(Keys.CONTROL + "\t");//to move focus to next tab in same browser
    try {
        Thread.sleep(8000);
    } catch (InterruptedException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    //to wait some time in that tab
    e.sendKeys(Keys.CONTROL + "\t");//to switch the focus to old tab again

J'espère que cela vous aide ..

3
Vishwak

La première chose à faire est d'ouvrir un nouvel onglet et d'enregistrer son nom de descripteur. Il sera préférable de le faire en utilisant du javascript et non des clés (ctrl + t) car les clés ne sont pas toujours disponibles sur les serveurs d'automatisation. Exemple:

public static String openNewTab(String url) {
    executeJavaScript("window.parent = window.open('parent');");
    ArrayList<String> tabs = new ArrayList<String>(bot.driver.getWindowHandles());
    String handleName = tabs.get(1);
    bot.driver.switchTo().window(handleName);
    System.setProperty("current.window.handle", handleName);
    bot.driver.get(url);
    return handleName;
}

La deuxième chose que vous devez faire est de basculer entre les onglets. Ne le faites que par les poignées de la fenêtre du commutateur, cela ne fonctionnera pas toujours car l'onglet sur lequel vous allez travailler ne sera pas toujours au point et Selenium échouera de temps en temps . clés, et javascript ne supporte pas vraiment la commutation d'onglets, j'ai donc utilisé des alertes pour changer d'onglet et cela a fonctionné comme un charme:

public static void switchTab(int tabNumber, String handleName) {
        driver.switchTo().window(handleName);
        System.setProperty("current.window.handle", handleName);
        if (tabNumber==1)
            executeJavaScript("alert(\"alert\");");
        else
            executeJavaScript("parent.alert(\"alert\");");
        bot.wait(1000);
        driver.switchTo().alert().accept();
    }
2
Ed Ram
driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL,Keys.SHIFT,Keys.TAB);

Cette méthode facilite la commutation entre plusieurs fenêtres. Le problème de cette méthode est qu’elle ne peut être utilisée que très souvent, jusqu’à ce que la fenêtre requise soit atteinte. J'espère que ça aide.

1
Anand Ramamurthy

Avec Selenium 2.53.1 utilisant firefox 47.0.1 en tant que WebDriver en Java: quel que soit le nombre d'onglets que j'ai ouverts, "driver.getWindowHandles ()" ne renverrait qu'un seul handle, il était donc impossible de basculer entre les onglets.

Une fois que j'ai commencé à utiliser Chrome 51.0, je pouvais obtenir tous les descripteurs. Le code suivant montre comment accéder à plusieurs pilotes et à plusieurs onglets dans chaque pilote.

// INITIALIZE TWO DRIVERS (THESE REPRESENT SEPARATE CHROME WINDOWS)
driver1 = new ChromeDriver();
driver2 = new ChromeDriver();

// LOOP TO OPEN AS MANY TABS AS YOU WISH
for(int i = 0; i < TAB_NUMBER; i++) {
   driver1.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL + "t");
   // SLEEP FOR SPLIT SECOND TO ALLOW DRIVER TIME TO OPEN TAB
   Thread.sleep(100);

// STORE TAB HANDLES IN ARRAY LIST FOR EASY ACCESS
ArrayList tabs1 = new ArrayList<String> (driver1.getWindowHandles());

// REPEAT FOR THE SECOND DRIVER (SECOND CHROME BROWSER WINDOW)

// LOOP TO OPEN AS MANY TABS AS YOU WISH
for(int i = 0; i < TAB_NUMBER; i++) {
   driver2.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL + "t");
   // SLEEP FOR SPLIT SECOND TO ALLOW DRIVER TIME TO OPEN TAB
   Thread.sleep(100);

// STORE TAB HANDLES IN ARRAY LIST FOR EASY ACCESS
ArrayList tabs2 = new ArrayList<String> (driver1.getWindowHandles());

// NOW PERFORM DESIRED TASKS WITH FIRST BROWSER IN ANY TAB
for(int ii = 0; ii <= TAB_NUMBER; ii++) {
   driver1.switchTo().window(tabs1.get(ii));
   // LOGIC FOR THAT DRIVER'S CURRENT TAB
}

// PERFORM DESIRED TASKS WITH SECOND BROWSER IN ANY TAB
for(int ii = 0; ii <= TAB_NUMBER; ii++) {
   drvier2.switchTo().window(tabs2.get(ii));
   // LOGIC FOR THAT DRIVER'S CURRENT TAB
}

J'espère que cela vous donne une bonne idée de la façon de manipuler plusieurs onglets dans plusieurs fenêtres de navigateur.

1
Charles Woodson

Puisque le driver.window_handles n’est pas en ordre, une meilleure solution est la suivante.

commencez par basculer vers le premier onglet en utilisant le raccourci Control + X pour basculer vers l'onglet 'x' dans la fenêtre du navigateur.

driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL + "1");
# goes to 1st tab

driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL + "4");
# goes to 4th tab if its exists or goes to last tab.
1
Natesh bhat

classe publique TabBrowserDemo {

public static void main(String[] args) throws InterruptedException {
    System.out.println("Main Started");
    System.setProperty("webdriver.gecko.driver", "driver//geckodriver.exe");
    WebDriver driver = new FirefoxDriver();
    driver.get("https://www.irctc.co.in/eticketing/userSignUp.jsf");
    driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);

    driver.findElement(By.xpath("//a[text()='Flights']")).click();
    waitForLoad(driver);
    Set<String> ids = driver.getWindowHandles();
    Iterator<String> iterator = ids.iterator();
    String parentID = iterator.next();
    System.out.println("Parent WIn id " + parentID);
    String childID = iterator.next();
    System.out.println("child win id " + childID);

    driver.switchTo().window(childID);
    List<WebElement> hyperlinks = driver.findElements(By.xpath("//a"));

    System.out.println("Total links in tabbed browser " + hyperlinks.size());

    Thread.sleep(3000);
//  driver.close();
    driver.switchTo().window(parentID);
    List<WebElement> hyperlinksOfParent = driver.findElements(By.xpath("//a"));

    System.out.println("Total links " + hyperlinksOfParent.size());

}

public static void waitForLoad(WebDriver driver) {
    ExpectedCondition<Boolean> pageLoadCondition = new
            ExpectedCondition<Boolean>() {
                public Boolean apply(WebDriver driver) {
                    return ((JavascriptExecutor)driver).executeScript("return document.readyState").equals("complete");
                }
            };
    WebDriverWait wait = new WebDriverWait(driver, 30);
    wait.until(pageLoadCondition);
}
0
Aravind HB

S'il vous plaît voir ci-dessous:

WebDriver driver = new FirefoxDriver();

driver.manage().window().maximize();
driver.get("https://www.irctc.co.in/");
String oldTab = driver.getWindowHandle();

//For opening window in New Tab
String selectLinkOpeninNewTab = Keys.chord(Keys.CONTROL,Keys.RETURN); 
driver.findElement(By.linkText("Hotels & Lounge")).sendKeys(selectLinkOpeninNewTab);

// Perform Ctrl + Tab to focus on new Tab window
new Actions(driver).sendKeys(Keys.chord(Keys.CONTROL, Keys.TAB)).perform();

// Switch driver control to focused tab window
driver.switchTo().window(oldTab);

driver.findElement(By.id("textfield")).sendKeys("bangalore");

J'espère que c'est utile!

0
Prashant

La faille avec la réponse sélectionnée est qu’elle suppose inutilement l’ordre dans webDriver.getWindowHandles(). La méthode getWindowHandles() renvoie une Set, qui ne garantit pas l'ordre. 

J'ai utilisé le code suivant pour changer les onglets, ce qui ne suppose aucun ordre. 

String currentTabHandle = driver.getWindowHandle();
String newTabHandle = driver.getWindowHandles()
       .stream()
       .filter(handle -> !handle.equals(currentTabHandle ))
       .findFirst()
       .get();
driver.switchTo().window(newTabHandle);
0

Cela fonctionnera pour MacOS pour Firefox et Chrome:

// opens the default browser tab with the first webpage
driver.get("the url 1");
thread.sleep(2000);

// opens the second tab
driver.findElement(By.cssSelector("Body")).sendKeys(Keys.COMMAND + "t");
driver.get("the url 2");
Thread.sleep(2000);

// comes back to the first tab
driver.findElement(By.cssSelector("Body")).sendKeys(Keys.COMMAND, Keys.SHIFT, "{");
0
ramy

J'ai eu un problème récemment, le lien a été ouvert dans un nouvel onglet, mais Selenium s'est concentré sur l'onglet initial.

J'utilise Chromedriver et le seul moyen de me concentrer sur un onglet était d'utiliser switch_to_window().

Voici le code Python:

driver.switch_to_window(driver.window_handles[-1])

Le conseil est donc de trouver le nom du handle de fenêtre dont vous avez besoin, ils sont stockés sous forme de liste dans

driver.window_handles
0
Kee

Pour obtenir des poignées de fenêtre parent. 

String parentHandle = driverObj.getWindowHandle();
public String switchTab(String parentHandle){
    String currentHandle ="";
    Set<String> win  = ts.getDriver().getWindowHandles();   

    Iterator<String> it =  win.iterator();
    if(win.size() > 1){
        while(it.hasNext()){
            String handle = it.next();
            if (!handle.equalsIgnoreCase(parentHandle)){
                ts.getDriver().switchTo().window(handle);
                currentHandle = handle;
            }
        }
    }
    else{
        System.out.println("Unable to switch");
    }
    return currentHandle;
}
0
Ankit Gupta

C'est un processus très simple: supposons que vous avez deux onglets, vous devez donc d'abord fermer l'onglet en cours en utilisant client.window(callback) car la commande switch "passe au premier disponible". Ensuite, vous pouvez facilement changer d’onglet à l’aide de client.switchTab.

0
Ravi Ubana

Un bref exemple de la façon de basculer entre les onglets dans un navigateur (dans le cas d’une fenêtre):

// open the first tab
driver.get("https://www.google.com");
Thread.sleep(2000);

// open the second tab
driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL + "t");
driver.get("https://www.google.com");
Thread.sleep(2000);

// switch to the previous tab
driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL + "" + Keys.SHIFT + "" + Keys.TAB);
Thread.sleep(2000);

J'écris Thread.sleep(2000) juste pour avoir un délai d'attente pour voir basculer entre les onglets.

Vous pouvez utiliser CTRL + TAB pour passer à l'onglet suivant et CTRL + MAJ + TAB pour passer à l'onglet précédent.

0
Stas
protected void switchTabsUsingPartOfUrl(String platform) {
    String currentHandle = null;
    try {
        final Set<String> handles = driver.getWindowHandles();
        if (handles.size() > 1) {
            currentHandle = driver.getWindowHandle();
        }
        if (currentHandle != null) {
            for (final String handle : handles) {
                driver.switchTo().window(handle);
                if (currentUrl().contains(platform) && !currentHandle.equals(handle)) {
                    break;
                }
            }
        } else {
            for (final String handle : handles) {
                driver.switchTo().window(handle);
                if (currentUrl().contains(platform)) {
                    break;
                }
            }
        }
    } catch (Exception e) {
        System.out.println("Switching tabs failed");
    }
}

Appelez cette méthode et transmettez au paramètre une sous-chaîne d'URL de l'onglet vers lequel vous souhaitez basculer.

0
Rahul Rana

Réponse simple qui a fonctionné pour moi:

for (String handle1 : driver1.getWindowHandles()) {
        System.out.println(handle1); 
        driver1.switchTo().window(handle1);     
}
0
Omar Lari