[Small North de programming notes]: Lesson 07-selenium for C # window processing

Source: Internet
Author: User

In the actual automated testing process, we will meet many situations that require the processing of Windows. For example, when you click Delete a message, the system displays an alert box. Or when you click a hyperlink, a new page opens in the browser. This article, to share with you the Selenium Webdriver window processing related APIs. Well, let's take a look at the main topics covered in this article as usual:

    • Window Processing interface: Itargetlocator
    • Browser Popup processing (new page)
    • JavaScript popup processing: Alert, Confirm, Prompt
    • Processing of inline frames: frame, iFrame
(a) Window processing interface: Itargetlocator

The Selenium webdriver Processing window capability is primarily provided by objects returned by the SwitchTo () method of the Webdriver object. This object implements the Itargetlocator interface and basically covers all the situations described in this article (i.e., the processing of popup windows, JS modal windows, inline frames). We can get the currently driven Itargetlocator object with the following code:

1         /// <summary>2         ///demo1: Get target anchored object3         /// </summary>4[Fact (DisplayName ="Cnblogs.WindowProcess.Demo1", Skip ="Just Demo")]5          Public voidWindowprocess_demo1 ()6         {7             //1. Get the window anchor object8Iwebdriver Driver =Newfirefoxdriver ();9             //omit part of the code ...TenItargetlocator Locator =driver. SwitchTo (); One             //Follow-up action ... A driver. Close (); -}

The definition of the Itargetlocator interface is as follows, and here I'll briefly describe the effects of these methods (described later in this article):

    • Activeelement: Gets the element with the current focus, if no element holding the focus returns the Body element (this method is not related to window processing ).
    • Alert: Switch to the modal window of JS popup.
    • Defaultcontent: Gets the frame on the first page and, when there is a iframes, gets the document for the main page.
    • Frame: This method has three overloaded implementations that are used to switch to the frame.
    • Parentframe: Select the parent frame to get the current page.
    • window: Toggles windows.
1     //Summary:2     //defines the interface through which the user can locate a given frame or3     //window.4      Public InterfaceItargetlocator5     {6 iwebelement activeelement ();7 Ialert Alert ();8 iwebdriver defaultcontent ();9Iwebdriver Frame (intFrameIndex);Ten iwebdriver Frame (iwebelement frameelement); OneIwebdriver Frame (stringframename); A iwebdriver parentframe (); -Iwebdriver Window (stringwindowname); -}

(ii) Processing of browser pop-up Windows (New page)

As described in the previous section, the Selenium Webdriver handles pop-up windows primarily through itargetlocator. Window method. Here I would like to introduce you to the selenium webdriver commonly used in the window positioning method:

    • Locating with Window name
    • Positioning pages with title and window handles
@ Position with window name

Referring to the definition of the Itargetlocator.window method, the method accepts the name of a window. So we can switch to that window by the name of the window (provided the developer defines the name of the window):

1             //1. Get the window anchor object2Iwebdriver Driver =Newfirefoxdriver ();3             //omit part of the code ...4Itargetlocator Locator =driver. SwitchTo ();5             Driver = Locator. Window ("windowname"); 6             //Follow-up action ...7Driver. Quit ();

We can switch windows through the above code, but the question is, how do we get the name of the window? All browsers have command-line tools to execute JS script, we just need to enter "window.name" to see the name of the current window, is my operation in the Firebug:

@ position page with Title and window handle

In many cases, the developer does not define a name for each popup window (in fact, it is not necessary). So, we need to use another way to locate our target window, the following code uses the window handle and the title to locate the window that needs to be accessed, we can get all the handles opened by the current browser through the Windowhandles property of the Webdriver object. Determine which handle is the interface handle that needs to be manipulated, depending on the specific condition of the page, which is the caption used here. In general, we need to save the current page handle so that it is easy to return to the current page after the operation is complete. The demo finally verifies that the title of the Operation page is correct, the code is as follows:

1         /// <summary>2         ///Demo2: Positioning elements by Title3         /// </summary>4[Fact (DisplayName ="Cnblogs.WindowProcess.Demo2")]5          Public voidWindowprocess_demo2 ()6         {7             varArticleName ="[small North de programming notes]: Lesson 02-selenium for C # core Objects";8 9_output. WriteLine ("Step 01: Launch the browser and open lesson 01-selenium for C #");TenIwebdriver Driver =Newfirefoxdriver (); OneDriver. URL ="http://www.cnblogs.com/NorthAlan/p/5155915.html"; A  -_output. WriteLine ("Step 02: Click on the link to open a new page. "); -             varLNKARTICLE02 =driver. Findelement (By.linktext (ArticleName)); the Lnkarticle02.click (); -  -_output. WriteLine ("Step 03: Get a handle to a new page based on the title. "); -             varOldwinhandle =driver. Currentwindowhandle; +             foreach(varWinhandleinchdriver. Windowhandles) -             { + driver. SwitchTo (). Window (winhandle); if  (driver. Title.contains (articlename))  at                 { -                     Break; -                 } -             } -  -_output. WriteLine ("Step 04: Verify that the new page title is correct. "); in             varArticleTitle = driver. Findelement (By.id ("Cb_post_title_url")); -assert.equal<string>(ArticleName, articletitle.text); to  +_output. WriteLine ("Step 05: Close the browser. "); - driver. Quit (); the}

It is worth noting that the 22nd line of code uses the content of the title as the criteria for judging whether the new page is open, and here you can use the URL or page content according to the actual needs ... and other conditions to judge.

(c) Processing of JavaScript popup boxes

Anyone with a little web programming experience should know that JavaScript can pop up modal dialogs. Before we go into the process of dealing with these pop-up forms, let's review the types of pop-up boxes that are built into the browser:

    • Alert: Only text and a message and a confirmation button (to prompt the user).
    • Confirm: More than Alert a Cancel button (used to confirm information to the user).
    • Prompt: More than confirm a text input box (you can get user input while confirming information to the user)
    • Authenticationcredentials: The window used to enter the user name and password (not given in).

OK, now let's start with how to handle these popup boxes. We mentioned Itargetlocatorabove. The alert method can be used to manipulate modal windows. The return object of the method implements the Ialert interface:

1     //Summary:2     //defines the interface through which the user can manipulate JavaScript alerts.3      Public InterfaceIalert4     {5         stringText {Get; }6         voidAccept ();7         voidDismiss ();8         voidSendKeys (stringkeystosend);9         voidSetauthenticationcredentials (stringUserName,stringpassword);Ten}

Here, it is necessary to clarify that the previous four pop-up windows are described using objects that implement the Ialert interface (that is, confirm,prompt,authenticationcredentials can be processed with objects that implement the Ialert interface):

    • Text: Get pop-up box textual information (for all modal windows)
    • Accept: Click the OK button (for all modal windows)
    • Dismiss: Click the Cancel button (for confirm,prompt,authenticationcredentials)
    • SendKeys: Enter text information (for prompt)
    • Setauthenticationcredentials: Set user name and password (for authenticationcredentials)

is not so ... easy? Here is the usual way to look at the specific use of code:

1Ialert alert = driver. SwitchTo (). Alert ();//go to pop-up box2Alert. Accept ();//OK: Alert, Confirm, Prompt3Alert. Dismiss ();//Cancel: Confirm, Prompt4       varText = alert. Text;//Get tips: Alert, Confirm, Prompt5Alert. SendKeys ("input text.");//Enter hint text: Prompt
(iv) Processing of inline frames

At the end of this article, let me introduce you to the processing of inline frames for Web pages. Some early B/s systems use IFRAME and frame for layout and nesting of pages. Previously, there was also the design of using an IFRAME to build a global popup box. Therefore, if your product has been in the history for many years. Well, you might need to deal with this part of the content. In fact, frame and iframe processing and window is very similar, here I simply give a demo:

1Itargetlocator Tagetlocator =driver. SwitchTo ();2Tagetlocator.frame (1);//Frame index.3Tagetlocator.frame ("FrameName");//frame frame name.4 5Iwebelement frame = driver. Findelement (by. Id ("Frameid or Iframeid" ));6       Tagetlocator.frame (Frame);7Tagetlocator.defaultcontent ();

As you can see from the code above, you can use index,frame name or the frame object to switch driver to the frame.

Summary: This article mainly describes how to use the Selenium webdriver core Itargetlocator interface processing various windows.

    • Window Processing interface: Itargetlocator
    • Browser Popup processing (new page)
    • JavaScript popup processing: Alert, Confirm, Prompt
    • Processing of inline frames: frame, iFrame

"Selenium for C #" related article: Click here.

    • [Small North de programming notes]: Lesson 01-selenium for C # Environment construction
    • [Small North de programming notes]: Lesson 02-selenium for C # core objects
    • [Small North de programming notes]: Lesson 03-selenium for C # element positioning
    • [Small North de programming notes]: Lesson 04-selenium for C # API
    • [Small North de programming notes]: Lesson 05-selenium for C # API
    • [Small North de programming notes]: Lesson 06-selenium for C # Process Control
    • [Small North de programming notes]: Lesson 07-selenium for C # window processing
    • [Small North de programming notes]: Lesson 08-selenium for C # pagefactory
    • [Small North de programming notes]: Lesson 09-selenium for C # Summary


When I finish publishing a post with no hyperlinks, I'll add the appropriate links to list the directories first.

Demo Address: Https://github.com/DemoCnblogs/Selenium

If you think this article is good or something, you can click on the bottom right corner of the "Recommended" button, because your support is I continue to write, share the most power! Small North @north Source: Http://www.cnblogs.com/NorthAlan Statement: The original text of this blog only represents my work in a certain time to summarize the views or conclusions, and I do not have a direct interest in the unit. Non-commercial, unauthorized, post please keep the status quo, reprint must retain this paragraph statement, and in the article page obvious location to the original connection.

[Small North de programming notes]: Lesson 07-selenium for C # window processing

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.