Selenium2.0 WebDriver Getting Started Guide

Source: Internet
Author: User

Selenium2.0 WebDriver Getting Started Guide

From: http://my.oschina.net/willSoft/blog/28119

 

1.1 download the Lib package of selenium2.0

Http://code.google.com/p/selenium/downloads/list

Official User Guide: http://seleniumhq.org/docs/

1.2 open a browser with WebDriver

Our commonly used browsers include Firefox and IE. Firefox is a mature browser supported by selenium. However, the page testing speed is usually very slow, seriously affecting the speed of continuous integration. htmlunit is recommended in this case. However, the interface cannot be seen during htmlunitdirver running, which is inconvenient for debugging. Which browser can be used for configuration items and flexible configuration as needed.

 

  1. Open the Firefox browser:

// Create a newinstance of the Firefox driver

WebDriver driver = newfirefoxdriver ();

  1. Open IE browser

// Create a newinstance of the Internet Explorer driver

WebDriver driver = newinternetexplorerdriver ();

Open htmlunit Browser

// Createa new instance of the Internet Explorer driver

Webdriverdriver = new htmlunitdriver ();

1.3 open the test page

For page-to-test, you first need to open the address of the page to be tested (such as the http://www.google.com), The get method provided by the web driver can open a page:

// And now use thedriver to visit Google

Driver. Get ("http://www.google.com ");

 

1.4 How to Find page elements

The findelement method of WebDriver can be used to find an element of a page. The most common method is to search by ID and name.

Assume that the page is written as follows:

<Input type = "text" name = "passwd" id = "passwd-ID"/>

The page elements can be found as follows:

Search by ID:

Webelement element = driver. findelement (by. ID ("passwd-ID "));

Or search by name:

Webelement element = driver. findelement (by. Name ("passwd "));

Or use XPath to find:

Webelement element = driver. findelement (by. XPath ("// input [@ ID = 'passwd-id']");

However, page elements are often not found because they are slow. We recommend that you wait for a time interval when searching.

1.5 how to operate on page elements

After finding the page element, how does one operate the page? We can describe the elements of different types one by one.

1.5.1 input box (text field or textarea)

Find the element in the input box:

Webelement element = driver. findelement (by. ID ("passwd-ID "));

Enter the following content in the input box:

Element. sendkeys ("test ");

Clear the input box:

Element. Clear ();

Obtain the text in the input box:

Element. gettext ();

 

1.5.2 select)

Find the element in the drop-down box:

Select select = new select (driver. findelement (by. ID ("select"); select the corresponding options:

Select. selectbyvisibletext ("mediaagencya ");

Or

Select. selectbyvalue ("ma_id_001 ");

Do not select the corresponding selection items:

Select. deselectall ();

Select. deselectbyvalue ("ma_id_001 ");

Select. deselectbyvisibletext ("mediaagencya ");

Or obtain the value of the selected item:

Select. getallselectedoptions ();

Select. getfirstselectedoption ();

 

1.5.3 single-choice (radio button)

Find the single sequence element:

Webelement bookmode = driver. findelement (by. ID ("bookmode "));

Select a single option:

Bookmode. Click ();

Clear a single option:

Bookmode. Clear ();

Determine whether a single option has been selected:

Bookmode. isselected ();

1.5.4 multiple options (checkbox)

The operations with multiple options are similar to those with one choice:

Webelement checkbox = driver. findelement (by. ID ("mycheckbox ."));

Checkbox. Click ();

Checkbox. Clear ();

Checkbox. isselected ();

Checkbox. isenabled ();

1.5.5 button)

Find the button element:

Webelement savebutton = driver. findelement (by. ID ("save "));

Click:

Savebutton. Click ();

Determine whether the button is enable:

 

Savebutton. isenabled ();

1.5.6 selection box

That is, the options on the left are available. After selection, move them to the right box, and vice versa. For example:

Select lang = new select (driver. findelement (by. ID ("Ages ")));

Lang. selectbyvisibletext ("English ");

Webelement addlanguage = driver. findelement (by. ID ("addbutton "));

Addlanguage. Click ();

1.5.7 pop-up dialog box (popup dialogs)

Alert = driver. switchto (). Alert ();

Alert. Accept ();

Alert. Dismiss ();

Alert. gettext ();

1.5.8 form)

The operations on elements in form are the same as those on other elements. After the operations on elements are completed, you can submit the form:

Webelement approve = driver. findelement (by. ID ("approve "));

Approve. Click ();

Or

Approve. Submit (); // only applicable to form submission

1.5.9 upload files

Upload File element operations:

Webelement adfileupload = driver. findelement (by. ID ("WAP-upload "));

String filepath = "C: \ test \ uploadfile \ media_ads \ test.jpg ";

Adfileupload. sendkeys (filepath );

1.6 switching between windows and frames

Generally, it is recommended that you log on first:

Driver. switchto (). defaultcontent ();

Switch to a frame:

Driver. switchto (). Frame ("leftframe ");

Switch from one frame to another:

Driver. switchto (). Frame ("mainframe ");

Switch to a window:

Driver. switchto (). Window ("windowname ");

 

1.7 call Java Script

The Web driver calls java scripts through javascriptexecutor. For example:

Javascriptexecutor JS = (javascriptexecutor) driver;

Js.exe cutescript ("(function () {inventorygridmgr. settablefieldvalue ('" + inventoryid + "', '" + fieldname + "','"

+ Value + "');})()");

1.8 page waiting

Page operations are slow. It usually takes some time for the page elements to appear. However, WebDriver does not provide a ready-made method and you need to write it yourself.

Wait for a while before performing operations on the page elements:

Public void waitforpagetoload (longtime ){

Try {

Thread. Sleep (time );

} Catch (effectione ){

}

}

Wait for the webelement:

Public webelementwaitfindelement (){

Returnwaitfindelement (by, long. parselong (commonconstant. gui_find_element_timeout), long

. Parselong (commonconstant. gui_find_element_interval ));

}

 

Public webelementwaitfindelement (by, long timeout, long interval ){

Long start = system. currenttimemillis ();

While (true ){

Try {

Return driver. findelement ();

} Catch (nosuchelementexception AUC ){

If (system. currenttimemillis ()-Start> = timeout ){

Throw newerror ("Timeout reached and element [" + by + "] Not Found ");

} Else {

Try {

Synchronized (this ){

Wait (interval );

}

} Catch (interruptedexception e ){

E. printstacktrace ();

}

}

}

}

}

 

1.9 use the API of selenium1.0 in selenium2.0

Selenium2.0 uses the wedriver API to operate on the page. Its biggest advantage is that it can run without installing a selenium server, but the page operation is not as convenient as selenium rc api of selenium1.0. Selenium2.0 provides methods to use the selenium rc api:

// You may use any WebDriver implementation. Firefox is used hereas an example

WebDriver driver = new firefoxdriver ();

 

// A "base URL", used by selenium to resolve relativeurls

String baseurl = "http://www.google.com ";

 

// Create the selenium implementation

Selenium selenium = new webdriverbackedselenium (driver, baseurl );

 

// Perform actions with Selenium

Selenium. Open ("http://www.google.com ");

Selenium. Type ("name = Q", "Cheese ");

Selenium. Click ("name = btng ");

 

// Get the underlying WebDriver implementation back. This willrefer to

// Same WebDriver instance as the "driver" variableabve.

WebDriver driverinstance = (webdriverbackedselenium) selenium). getunderlyingwebdriver ();

 

// Finally, close thebrowser. Call stop on the webdriverbackedselenium instance

// Instead of callingdriver. Quit (). Otherwise, the JVM will continue running after

// The browser has beenclosed.

Selenium. Stop ();

 

I used the WebDriver API and seleniumrc API to write a login script. Obviously, the latter operation is simpler and clearer.

Login script written by WebDriver API:

Public void login (){

Driver. switchto (). defaultcontent ();

Driver. switchto (). Frame ("mainframe ");

 

Webelement eusername = waitfindelement (by. ID ("username "));

Eusername. sendkeys (manager@ericsson.com );

 

Webelement epassword = waitfindelement (by. ID ("password "));

Epassword. sendkeys (manager );

 

Webelementeloginbutton = waitfindelement (by. ID ("loginbutton "));

Eloginbutton. Click ();

 

}

The login script written by seleniumrc API:

Public void login (){

Selenium. selectframe ("relative = Top ");

Selenium. selectframe ("mainframe ");

Selenium. Type ("username", "manager@ericsson.com ");

Selenium. Type ("password", "manager ");

Selenium. Click ("loginbutton ");

}

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.