![](/img/trans.png)
[英]open new tab(not link in new tab) in Chrome and focus on it Selenium java
[英]Selenium Java New Tab in Chrome - won't open , keeps opening URL`s in same tab
package javaapplication1;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class JavaApplication1 {
public static void main(String[] args) throws InterruptedException {
System.setProperty("webdriver.chrome.driver", "C:\\Users\\Aca\\desktop\\chromedriver.exe");
// Initialize driver
WebDriver driver = new ChromeDriver();
//Maximize browser window
driver.manage().window().maximize();
//Go to URL
driver.get("http://www.google.com");
//Set timeout
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
// Open new tab – May be you are stuck here
driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL + "t");
//Go to URL
driver.get("http://www.gmail.com");
//Set new tab timeout
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
}
}
我試圖打開一個新選項卡,而保持上一個選項卡處於打開狀態..我無法打開一個新選項卡。 它將打開URL保留在同一選項卡中。.我也嘗試使用操作。
您需要將驅動程序切換到新選項卡。 在Chrome中,其操作就像切換窗口一樣
String tabHandle = driver.getWindowHandle();
driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL + "t");
// switch to the new window
for (String handle : driver.getWindowHandles()) {
if (!handle.equals(tabHandle))
{
driver.switchTo().window(handle);
}
}
driver.get("http://www.gmail.com");
// close the new tab and switch back to the old one
driver.close();
driver.switchTo().window(tabHandle);
附帶說明一下, implicitlyWait
等待是為驅動程序而不是選項卡/窗口定義的。 打開新標簽后,無需再次定義它。
這是chromedriver本身的問題。 查看提交的相關錯誤
您忘記了在導航之前將驅動程序的焦點更改為新選項卡。
打開新標簽后,請嘗試以下操作:
driver.sendKeys(Keys.chord(Keys.CONTROL,"t"));
ArrayList<String> tabs = new ArrayList<String>(driver.getWindowHandles()); //Get tabs
driver.switchTo().window(tabs.get(1)); //Navigate to new tab
driver.get("http://www.gmail.com"); //Navigate within new tab
driver.close(); //Close the tab when done
driver.switchTo().window(tabs.get(0)); //Navigate to original tab
請嘗試使用Selenium Java在Chrome中打開新標簽頁。
package com.sample;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
public class NewWindow {
public static void main (String[] args){
System.setProperty ("webdriver.chrome.driver", "C:\\Chrome Driver\\chromedriver.exe");
ChromeOptions options = new ChromeOptions();
options.addArguments("disable-arguments");
WebDriver driver = new ChromeDriver();
driver.get("https://www.google.com");
((JavascriptExecutor) driver).executeScript("window.open('http://facebook.com/');");
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.