selenium。 如何切换到一个窗口谁的URL包含某个子字符串?

由于Selenium操作,我打开了三个窗口。 我需要切换到谁的URL包含子串“Servlet”的窗口

driver.switchTo().window("*Servlet*"); 

我该如何正确编码?

我最近做了类似的事情……这里有一段摘录。 (我将它从标题移植到Url。)

driver.switchTo().window("*Servlet*");

不幸的是,它并不那么容易..我们不能在那里指定通配符..所以让我们为它做一些function –

  /** * Waits for a window with a desired url to come up.
* If it does not come up in 5 seconds, it will fail. *
*
* This method will set the current active window to the window requested. If you need to switch back to the previous window, use {@link #switchToWindow(String)} * @param regex The title of the window. Regex enabled. * @return */ public void waitForWindow(String regex) { Set windows = getDriver().getWindowHandles(); for (String window : windows) { try { driver.switchTo().window(window); p = Pattern.compile(regex); m = p.matcher(driver.getCurrentUrl()); if (m.find()) return switchToWindow(regex); } catch(NoSuchWindowException e) { if (attempts <= 5) { attempts++; Thread.sleep(1); return waitForWindow(regex); } else { fail("Window with url: " + regex + " did not appear after 5 tries. Exiting."); // found } } } // when we reach this point, that means no window exists with that title.. if (attempts == 5) { fail("Window with title: " + regex + " did not appear after 5 tries. Exiting."); return (T) this; } else { System.out.println("#waitForWindow() : Window doesn't exist yet. [" + regex + "] Trying again. " + attempts + "/5"); attempts++; return waitForWindow(regex); } }

切换到窗口,

  /** * Switches the current window based on title. * @param regex A regular expression window title. * @return */ public void switchToWindow(String regex) { Set windows = driver.getWindowHandles(); for (String window : windows) { getDriver().switchTo().window(window); System.out.println("#switchToWindow() : url=" + driver.getCurrentUrl()); p = Pattern.compile(regex); m = p.matcher(driver.getCurrentUrl()); if (m.find()) // found } fail("Couldn't switch to window with urlregex: " + regex + "!"); } 

在你的例子中,它是,

 waitForWindow(".*Servlet.*"); switchToWindow(".*Servlet.*"); 
 protected void switchTabsUsingPartOfUrl(String platform) { String currentHandle = null; try { final Set handles = driver.getWindowHandles(); if (handles.size() > 1) { currentHandle = driver.getWindowHandle(); } if (currentHandle != null) { for (final String handle : handles) { driver.switchTo().window(handle); if (currentUrl().contains(platform) && !currentHandle.equals(handle)) { break; } } } else { for (final String handle : handles) { driver.switchTo().window(handle); if (currentUrl().contains(platform)) { break; } } } } catch (Exception e) { System.out.println("Switching tabs failed"); } } 

只需调用此方法并传递要切换到的选项卡的url子字符串