Quick start of Selenium Multi-window switching method
Problem description: one of the most common problems encountered when executing scripts is that Unable to find element in selenium..., in addition to excluding page loading time, is a common mistake for beginners to click a button to jump to a new page. If you open it on the current page, give it enough time to load. But if the new window opens the page, Selenium will not automatically recognize the new window to find elements, so we need to simulate the artificial switch to the new window. WebDriver provides the switchTo (). Window () method to switch between different windows.
Solution:
1. First, confirm which step to switch the window after.
Switch before the next step operation.
two。 Encapsulation window switching method, eg. Here identify the window title to switch
The encapsulation method is as follows:
Public class WinSwitchUtil {
Public static boolean switchToWindow (WebDriver dr,String windowTitle) {
Boolean status = false
Try {
String currentHandle = dr.getWindowHandle ()
Set handles = dr.getWindowHandles ()
Iterator it = handles.iterator ()
While (it.hasNext ()) {
String s = it.next ()
If (s.equals (currentHandle))
Continue
Else {
Window (s) dr.switchTo ()
If (dr.getTitle () .contains (windowTitle)) {
Status = true
System.out.println ("Switch to window:"
+ windowTitle + "pass")
Break
} else
Continue
}
}
} catch (NoSuchWindowException e) {
System.out.println ("Window:" + windowTitle + "not found" + e.fillInStackTrace ())
Status = false
}
Return status
}
}
3. Call method
Boolean status = switchToWindow (dr, "New window title")
If (status) {
/ / tasks performed in the new window
}
4. If the actual business requires to return to the original window after the operation in the new window is completed, the method can be called again.
Boolean status = switchToWindow (dr, "original window title")
If (status) {
/ / tasks performed in the original window
}
5. The above are relatively simple business processing methods, if the complex business can be written to encapsulate a number of windows, according to the business to choose to call. It is also applicable to pop-up window business.