Computer >> Máy Tính >  >> Lập trình >> Java

Chuyển đổi các tab bằng Selenium WebDriver với Java.

Chúng ta có thể chuyển đổi các tab bằng Selenium. Đầu tiên, chúng ta phải mở một liên kết trong một tab mới. Các phím .chord method cùng với sendKeys sẽ được sử dụng. Phương thức Keys.chord cho phép bạn chuyển nhiều khóa cùng một lúc. Nhóm khóa hoặc chuỗi được chuyển làm đối số cho phương thức.

Chúng tôi sẽ chuyển Chìa khóa.CONTROL Keys.ENTER làm đối số cho phương thức Keys.chord. Sau đó, toàn bộ chuỗi được chuyển làm đối số cho sendKeys phương pháp. Cuối cùng, phương thức sendKeys phải được áp dụng trên liên kết được xác định bởi driver.findElement phương pháp.

Cú pháp

String clickl = Keys.chord(Keys.CONTROL,Keys.ENTER);
driver.findElement(By.xpath("//*[text()='Terms of Use']")). sendKeys(clickl);

Sau đó, giữ tất cả id cửa sổ đã mở trong ArrayList và chuyển tiêu điểm trình điều khiển sang tab mới bằng switchTo phương pháp. Sau đó, chuyển id cửa sổ của tab mới làm đối số cho phương thức đó.

Cuối cùng, sau khi thực hiện các tác vụ trên tab mới, chúng ta có thể chuyển trở lại cửa sổ mẹ bằng switchTo phương thức và chuyển id cửa sổ của cửa sổ mẹ làm đối số cho phương thức đó.

Hãy để chúng tôi chuyển đổi giữa hai tab -

Chuyển đổi các tab bằng Selenium WebDriver với Java.

Ví dụ

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
import java.util.List;
import java.util.ArrayList;
public class SwitchTab{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver",
      "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      driver.get("https://www.tutorialspoint.com/about/about_careers.htm");
      // wait of 5 seconds
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      // Keys.Chord string
      String clickl = Keys.chord(Keys.CONTROL,Keys.ENTER);
      // open the link in new tab, Keys.Chord string passed to sendKeys
      driver.findElement(
      By.xpath("//*[text()='Terms of Use']")).sendKeys(clickl);
      Thread.sleep(1000);
      // hold all window handles in array list
      ArrayList<String> newTb = new ArrayList<String>(driver.getWindowHandles());
      //switch to new tab
      driver.switchTo().window(newTb.get(1));
      System.out.println("Page title of new tab: " + driver.getTitle());
      //switch to parent window
      driver.switchTo().window(newTb.get(0));
      System.out.println("Page title of parent window: " + driver.getTitle());
      driver.quit();
   }
}

Đầu ra

Chuyển đổi các tab bằng Selenium WebDriver với Java.