簡體   English   中英

如何使用WebDriver中的Java將瀏覽器的控件帶到新打開的選項卡

[英]How can I take a browser's control to a newly opened tab using Java in WebDriver

//Go to a page where link is present 
driver.findElement(By.xpath("//div[@id='LftNav']/ul/li[3]/div/ul/li[3]/a/label"))).click();
//Click this link will open up a new tab.     
driver.findElement(By.xpath("//tr[2]/td[9]/a")).click();

//Now I have to verify a value present in the New Tab.

為此,我必須將控件傳遞給“新建”選項卡。 我該怎么做?

您可以使用以下功能切換選項卡(和完整的窗口):

ArrayList<String> windowHandles = new ArrayList<String> (driver.getWindowHandles());
driver.switchTo().window(windowHandles.get(1));

例:你只有兩個手柄。 如果要關閉標簽並返回,可以使用:

driver.close();
driver.switchTo().window(windowHandles.get(0));

如果您有兩個以上的標簽,則可以使用:

driver.getWindowHandles().size()

獲取打開的選項卡的數量,然后跳轉到size()-1

String mainWindow = driver.getWindowHandle(); // get the main window handle
driver.findElement(By.cssSelector("//*[#id='someId']")).click(); // click some link that opens a new window

for (String winHandle : driver.getWindowHandles()) {
    driver.switchTo().window(winHandle);
 // switch focus of WebDriver to the next found window handle (that's your newly opened window)
if(driver.findElement(By.Id("SomeID")).getText().equals("expected window title"))
break;
}

SendKeys對我不起作用。 我嘗試了下面對我有用的代碼:

WebDriver driver = new ChromeDriver();
driver.get("https://www.google.com/");
Robot robot = new Robot();
robot = new Robot();
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_T);  
robot.keyRelease(KeyEvent.VK_CONTROL);
robot.keyRelease(KeyEvent.VK_T);
Thread.sleep(3000);
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_TAB);  
robot.keyRelease(KeyEvent.VK_CONTROL);
robot.keyRelease(KeyEvent.VK_TAB);
int tabNo = driver.getWindowHandles().size();
System.out.println(tabNo);
ArrayList<String> windowHandles = new ArrayList<String> (driver.getWindowHandles());
driver.switchTo().window(windowHandles.get(tabNo-1)); 
driver.get("http://www.bing.com/");

暫無
暫無

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

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