2017-05-26 65 views
0

我想在瀏覽器中打開一個新的選項卡。 但是,它會在同一個標​​籤中打開第二個網址。無法在瀏覽器中打開新的選項卡。它加載第二個網址在同一個標​​籤

代碼:

import org.openqa.selenium.By; 
import org.openqa.selenium.Keys; 
import org.openqa.selenium.WebDriver; 
import org.openqa.selenium.chrome.ChromeDriver; 

public class ChromeFlock { 

    public static void main(String[] args) throws Exception {  WebDriver driver;  System.setProperty("webdriver.chrome.driver", "C:\\Automation\\chromedriver_win32\\chromedriver.exe");  driver = new ChromeDriver(); 
     driver.manage().window().maximize(); 

     String baseUrl = "http://www.google.co.uk/"; 
     driver.get(baseUrl); 

     Thread.sleep(3000); 

     String selectLinkOpeninNewTab = Keys.chord(Keys.CONTROL,"t"); 
     driver.findElement(By.tagName("body")).sendKeys(selectLinkOpeninNewTab); 

     driver.get("http://www.facebook.com"); } 

} 

回答

1

使用JavascriptExecutor如下:

((JavascriptExecutor) driver).executeScript("window.open('http://www.facebook.com');"); 
0

您可以使用鍵盤仿真:

new Actions(driver).sendKeys(Keys.Control + 'w').build.perform(); // or + 't' 
driver.get("http://www.facebook.com"); 

或使用JavaScriptExecutor:

((JavascriptExecutor) driver).ExecuteScript("window.open('http://www.facebook.com','_blank');"); 
+0

仍然是同樣的問題。打開第二個鏈接相同的標籤,而不是新的 –

+2

@FieryCat你的語法是錯誤的。 – kushal

+0

@ShaikhFarzan但你有以前的選項卡完成加載?嘗試增加超時時間 – FieryCat

1

也許你沒有切換到新選項卡,這會導致僅在父項選項卡上啓動第二個鏈接。

您可以使用Robot類來通過模擬按下鍵盤的Ctrl + t鍵來打開新選項卡。然後您需要使用driver.switchTo()命令切換到新選項卡

有關代碼段和詳細信息,請檢查此Open a new tab in Selenium

相關問題