我一直在尝试许多功能来打开我最近打开的选项卡中的链接,但是它不起作用。
带有示例性注释的最小可复制示例,说明每行之后发生的情况(这是使用Selenium Webdriver,Java):
driver.get("https://twitter.com") //opens twitter in tab 1(intended)
((JavascriptExecutor)driver).executeScript("window.open('https://google.com')"); //opens new tab (tab 2) then opens google.com(intended)
((JavascriptExecutor)driver).executeScript("window.location.replace('https://facebook.com')"); //opens facebook.com in tab 1 (unintended)
我希望Facebook在选项卡2中打开。
答案 0 :(得分:-1)
一旦打开https://twitter.com
作为基本URL,然后在相邻的tab中打开https://google.com
。接下来,您必须在tab的 WebDriverWait 引出的相邻numberOfWindowsToBe(2)中打开URL https://facebook.com
,可以使用以下解决方案:
代码块:
public class A_demo
{
public static void main(String[] args) throws Exception
{
System.setProperty("webdriver.chrome.driver", "C:\\Utility\\BrowserDrivers\\chromedriver.exe");
ChromeOptions options = new ChromeOptions();
options.addArguments("start-maximized");
options.setExperimentalOption("excludeSwitches", Collections.singletonList("enable-automation"));
options.setExperimentalOption("useAutomationExtension", false);
WebDriver driver = new ChromeDriver(options);
driver.get("https://twitter.com");
String parent_window = driver.getWindowHandle();
((JavascriptExecutor) driver).executeScript("window.open('https://google.com');");
new WebDriverWait(driver,5).until(ExpectedConditions.numberOfWindowsToBe(2));
Set<String> allWindows = driver.getWindowHandles();
for(String child_window:allWindows)
if(!parent_window.equalsIgnoreCase(child_window))
driver.switchTo().window(child_window);
driver.get("https://facebook.com");
driver.quit();
}
}