由于 Selenium 操作,我打开了三个窗口。我需要切换到 URL 包含子字符串“Servlet”的窗口
driver.switchTo().window("*Servlet*");
如何正确编码?
我最近做了类似的事情..这是摘录。(我把它从做标题移植到了 Url。)
driver.switchTo().window("*Servlet*");
不幸的是,这并不容易......我们不能在那里指定通配符......所以让我们为它制作一些函数 -
/**
* Waits for a window with a desired url to come up.<br>
* If it does not come up in 5 seconds, it will fail.
* <br>
* <br>
* 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<String> 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<String> 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<String> 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 子字符串