[Selenium] Basic use

Source: Internet
Author: User
Tags xpath selenium grid

1. Selenium Foundation


1.1 Selenium Introduction

Selenium is a series of web-based automated test tools that provide a series of test functions to support Web automation testing that can locate interface elements in a variety of ways and compare the expected results with the actual performance of the system. The selenium has several features:

1) Multi-browser can be tested, such as IE, Firefox, Safari, Chrome, mobile browser and so on.

2) support multiple languages, such as Java, C #, Python, Ruby, PHP, etc.

3) cross-platform, such as Windows, Linux, IOS, Android, etc.

4) Open source is free.


1.2 Selenium Tool Group

The selenium consists of several tools:

1) Selenium IDE

The Selenium IDE is a primary tool for building scripts, a Firefox plugin that has an easy-to-use interface with recording capabilities to record user actions and export to reusable scripts.

2) Selenium 1

Selenium 1 (Selenium RC) is one of Selenium's most important test tools, capable of writing test code in multiple languages while supporting almost all browser testing.

3) Selenium 2

Selenium 2 (Webdriver), the latest version of the tool, represents the direction of future Selenium, a new set of automated testing tools that provide many features, including a better organized, object-oriented API, and overcome the limitations of testing in the Selenium 1 release.

4) Selenium Grid

The Selenium grid enables testing of Selenium 1 to run in several different environments, as well as to allow tests to be executed in parallel. In other words, each test can run on a different machine at the same time.


2. Selenium IDE


2.1 Installing the IDE

Selenium IDE can be downloaded from http://seleniumhq.org/download/ , if the currently used browser is Firefox,firefox will automatically recognize it as a Firefox add-on download, after the download is over , prompt for the installation of the components as follows:

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M01/5B/6A/wKiom1UIFYjxSJllAAHk_iWMw3g983.jpg "title=" Selenium.jpg "alt=" Wkiom1uifyjxsjllaahk_iwmw3g983.jpg "/>

After the installation is complete, you can see the Selenium IDE entry in the menu by restarting the browser.


2.2 Recording Test Cases

Open the Selenium IDE, turn on recording by default, and click the red Circle button to cancel the recording as follows:

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M01/5B/A0/wKiom1UOp9myUwZDAAGx6RMlGGo099.jpg "title=" Selenium.jpg "alt=" Wkiom1uop9myuwzdaagx6rmlggo099.jpg "/>

The new use case needs to use the File menu, where the most frequently seen test cases and test Suite are in the menu. Typically, a set of related test cases is a test suite, which consists of multiple test case concatenation. When you open the Selenium IDE, the IDE has set up a test suite named "Untitled" by default.

To record Baidu search action as an example, first enter the address of Baidu in the base URL, then click the Record button, then open the Baidu home page in Firefox, enter the search keyword "Selenium", click "Baidu a Bit", return to the Selenium IDE and stop recording, You can see a few lines of new data added to the test steps table in testing suite as follows:

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M01/5B/A0/wKiom1UOqT-yE3mfAAJfCpC1kZo415.jpg "title=" Selenium.jpg "alt=" Wkiom1uoqt-ye3mfaajfcpc1kzo415.jpg "/>

The test steps table uses a keyword-driven test method that contains the following 3 columns:

1) Command: Indicates what action to perform.

2) Target: Indicates which interface element is to be manipulated.

3) Value: Indicates how much value is used for the operation.

In, the first line to the target "/" to open the Web page, the second row to find an element with the ID of KW, and then use the Type command to enter the content, enter the value of selenium, the third row to find the element ID su, and then execute the clickandwait command, first click, Then wait for the page to finish loading. Just click the Play button in the action bar to repeat the test, and use the Fast-slow slider to control the time interval at which each step in the test is performed.


2.3 Writing Test Cases

Once you understand how recording works, you can write a use case directly by writing a test steps table, now using Google testing.

Right-click on the Action steps table, select the Insert New command option, then edit, enter the Open command, and set target to "http://www.google.com.hk". Then insert a new line, enter a type in the command text box, enter ID=LST-IB in the target text box, and enter a value of selenium. Then insert the 3rd step, edit the click Command, and let the search button be clicked as follows:

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M02/5B/A1/wKiom1UOrHfTHikyAAKCD0i7y5U449.jpg "title=" Selenium.jpg "alt=" Wkiom1uorhfthikyaakcd0i7y5u449.jpg "/>


3. Command


3.1 Command Set

The command indicates what action to take, is a required parameter, and you can see all the commands by clicking the command drop-down list box. These selenium commands are often referred to as "Selenese", a set of commands that are used to perform tests that combine to form a test script.

In Selenese, some commands are based on HTML markup to test whether a UI element exists, to verify that the specified content is correct, to check whether the link is available, to enter fields, to select options for a list, to submit a form, and to manipulate the data in the table. Another part of the Selenium command is used for ancillary testing, such as verifying window size, mouse position, warning information, AJAX features, pop-ups, event handling, and various other Web application features, as follows:

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M01/5B/BB/wKiom1URWOyQS2XFAAIfKMQ_2Qg640.jpg "title=" Selenium.jpg "alt=" Wkiom1urwoyqs2xfaaifkmq_2qg640.jpg "/>

The selenium command can be divided into 3 classes: action (action), Accessor (store), and assertion (assertion). The action command is typically used to manipulate the state of an application. The accessor command checks the state of the application and stores the result in a variable. The assertion command is similar to the accessor command, but they verify the state of the application and confirm that the status matches the expected results.


3.2 Browser Actions

The action command is typically used to manipulate the application, which performs actions such as "click", "Select", "enter", and so on. The action command fails to run or an error occurs, which causes the test to be interrupted. Some with "... andwait "suffix" command, which is equivalent to a "waitforpagetoload" command after the original command, that is, after an operation is executed, wait for the page to refresh, you can also use the original command to add "Waitforpagetoload" way.

1) Open (URL): Opens the specified URL, which can be a relative URL or an absolute URL. The open command waits for the page to finish loading before executing the next command. When using open in the IDE, if the parameter target is empty, the filled-in page in BaseURL will open, and when target is not empty, the Baseurl+target page will be opened and BaseURL will be ignored when target starts with HTTP/. Open the URL in target directly.

2) GoBack (): This command is equivalent to clicking the Back button on the browser, because there are no parameters, target and value can not be filled.

3) Refresh (): This command is equivalent to clicking the Refresh button on the browser, because there are no parameters, target and value can not be filled.

4) Windowfocus (): The command is used to activate the currently selected browser window, and the target and value can be blank because there are no parameters.

5) Windowmaximize (): The command is used to maximize the currently selected browser window, and because there are no parameters, target and value can be filled out.

6) Close (): This command closes the currently selected browser window, and because there are no parameters, target and value can be filled out.


3.3 Basic operations

1) type (locator, value): This command is used to enter a value in an element of type input, as if it were entered with a keyboard. It can also be used to assign a value to a drop-down list box, check box.

2) Typekeys (locator, value): This command is used to simulate keystroke events and enter characters individually. Equivalent to calling the KeyDown, KeyUp, KeyPress and other events.

3) Click (Locator): Clicking a link, check box, or Radio box.

4) Clickat (Locator, coordstring): Similar to the click Command, but requires the relative coordinates to be filled in.

5) DoubleClick (Locator): Double-click the link, check box, or Radio box.

6) Doubleclickat (Locator, coordstring): Similar to DoubleClick, the difference is that the relative coordinates need to be filled in.

7) Select (Selectlocator, optionlocator): This command is used to select the specified option in the drop-down list box. The options are positioned differently than the drop-down boxes, "label=" matches based on the text of the option, "value=" is matched based on the actual value of the option, "id=" matches based on the ID of the option, and "index=" matches based on the index of the option. If there is no prefix, the default is a label match.

8) Check (Locator): Tick the check box or radio box, note that the check command does not trigger a click action.

9) Uncheck (Locator): In contrast to the function of the Check command, its role is to uncheck.

Focus (Locator): shifts the focus to the specified element.

In addition to the above, the Selenium IDE provides some commands for simulating keyboard and mouse actions, as follows:

Name Role
Altkeydown () Touch and hold down the ALT key until you call the Altkeyup command
Altkeyup () Release the ALT key
Controlkeydown () Simulates pressing the CTRL key until the Controlkeyup command is called
Controlkeyup ()
Release the CTRL key
Shiftkeydown () Simulates holding down the SHIFT key until the Shiftkeyup command is called
Shiftkeyup () Release the SHIFT key
KeyDown (Locator, Keysequence) Simulates pressing a key until the KeyUp command is executed
KeyPress (Locator, Keysequence) The analog user taps a key
KeyUp (Locator, Keysequence) Simulate releasing a key
MouseDown (Locator) Simulates the user pressing the left mouse button on the specified element
Mousedownat (Locator, coordstring) Similar to MouseDown, you need to fill in the coordinates
Mousedownright (Locator) Simulates the user pressing the right mouse button on the specified element
Mousedownrightat (Locator, coordstring) Similar to mousedownright, you need to fill in the coordinates
MouseUp (Locator) Release the left mouse button of the press
Mouseupat (Locator, coordstring) Similar to MouseUp, you need to fill in the coordinates
Mouseupright (Locator) Release the right mouse button of the press
Mouseuprightat (Locator, coordstring) Similar to mouseupright, you need to fill in the coordinates
MouseOver (Locator) Move the mouse cursor inside the specified element
MouseOut (Locator) Move the mouse cursor outside the specified element


3.4 Setting and controlling class actions

1) setTimeout (timeout): Specifies the maximum wait time for selenium to perform an operation, only for open commands, commands that start with waitfor, and commands with andwait suffixes. The default time-out is 30 seconds, and if the test is more than 30 seconds, an error is thrown.

2) Setspeed (value): Sets the execution speed of the test, which is the time interval between each test step. The default is no interval, and the interval time is 0 seconds.

3) Pause (waitTime): Causes the test to pause execution for a specified period of time.

4) Break (): Pauses the test being executed until the user manually clicks the Continue button.

5) captureentirepagescreenshot (filename, Kwargs): The current window is made and saved as a PNG file.

6) Highlight (Locator): Temporarily change the background color of the specified element to * * *, and then cancel the effect later.

7) Echo (message): Prints the specified information and is typically used for debugging.


3.5 Accessor

The accessor command checks the state of the application and stores the result in a variable. The accessor command can be used to automatically generate the assertion command, where the value of the variable can be read with "${name}".

1) Store (expression, variableName): This is the most basic way to store a specified value in a variable.

2) Storetitle (variableName): the title that is used to store the current page.

3) storelocation (variableName): The URL that is used to store the current page.

4) Storevalue (Locator, VariableName): Used to store values stored by input elements, such as text boxes, check boxes, and values in a radio box. For a check box or a radio box, the stored value becomes "on" or "off".

5) storeeditable (Locator, VariableName): Used to store the editable state of the input element, such as the editable state of a text box, check box, radio box, or True if editable, false otherwise.

6) Storetext (Locator, VariableName): A text value used to store an element, such as a link, plain text, and so on.

7) storechecked (Locator, VariableName): The check box is stored or the checkbox is checked, and the return value is true or false.

8) Storeselectedindex (Selectlocator, variableName): Gets the index of the selected item in the example table (starting from 0).

9) Storeselectedlabel (Selectlocator, variableName): Gets the text value of the selected item in the specified list.

Storeselectedvalue (Selectlocator, variableName): Gets the true value of the selected item in the specified list.

Storeselectoptions (Selectlocator, variableName): Gets the text of all the options in the specified list, separated by commas.

Storetable (Tablecelladdress, variableName): Gets the value of a cell in the table, with the row and column numbers starting with 0.

Storeattribute (Attributelocator, variableName): Gets the value of the specified property, note that target should fill in the positional expression of the property.

Storetextpresent (Pattren, VariableName): Verifies that the specified text appears in the page and returns True if it is, otherwise false.

Storeelementpresent (Locator, VariableName): Verifies that the specified element exists in the page, returns True if it is, otherwise false.

Storevisible (Locator, VariableName): Verifies that the specified element exists in the page, especially if the visibility property is a hidden or an invisible element with the display property of None.

Storespeed (VariableName): Gets the execution speed, which gets the execution interval between test steps.


3.6 Assertion

The assertion command is similar to the accessor command, but they are primarily used to verify whether a proposition is true, such as "an element exists." All assertion commands can be used in 3 modes: Assert, verify, and waitfor, such as Asserttext, Verifytext, and Waitfortext. If the assert fails and the test is interrupted, and the verify fails, the failure is recorded, but the test continues, it is recommended to use a single assert to confirm that the current application is on the correct page, and then use a series of VERIFY commands to test the value of the form field, the label value, and so on. The WAITFOR command is used to wait until the waiting condition is true, but if the wait time exceeds the current time-out setting, the waiting condition is still false, and the test fails and terminates.

1) asserttitle (pattern)/assertnottitle (pattern)/verifytitle (pattern)/verifynottitle (pattern)/Waitfortitle ( pattern)/Waitfornottitle: Verifies that the title of the page is equal to or not equal to the expected value.

2) assertlocation (pattern)/assertnotlocation (pattern)/verifylocation (pattern)/verifynotlocation (pattern)/ Waitforlocation (pattern)/waitfornotlocation (pattern): Verifies that the URL of the Web page is equal to or not equal to the expected value.

3) Assertvalue (locator, pattern)/assertnotvalue (locator, pattern)/verifyvalue (locator, pattern)/Verifynotvalue ( Locator, pattern)/waitforvalue (locator, pattern)/waitfornotvalue (locator, pattern): Verifies that the value of the INPUT element is equal to or not equal to the expected value.

4) asserteditable (Locator)/assertnoteditable (Locator)/verifyeditable (Locator)/verifynoteditable (Locator)/ Waitforeditable (Locator)/waitfornoteditable (Locator): verifies that the editable state of the input element is the expected state.

5) Asserttext (locator, pattern)/assertnottitle (locator, pattern)/verifytitle (locator, pattern)/Verifynottitle ( Locator, pattern)/waitfortitle (locator, pattern)/waitfornottitle (locator, pattern): Verifies that the title of the Web page is equal to or not equal to the expected value.

6) assertchecked (Locator)/assertnotchecked (Locator)/verifychecked (Locator)/verifynotchecked (Locator)/ waitforchecked (Locator)/waitfornotchecked (Locator): Verify that the check box or radio box is selected to match the expected status.

7) Assertselectedindex (Selectlocator, pattern)/Assertnotselectedindex (Selectlocator, pattern)/Verifyselectedindex (Selectlocator, pattern)/Verifynotselectedindex (Selectlocator, pattern)/Waitforselectedindex (Selectlocator, pattern)/Waitfornotselectedindex (Selectlocator, pattern): Verifies whether the index of the selected item in the list matches the expected value.

8) Assertselectedlabel (selectlocator, pattern)/Assertnotselectedlabel (Selectlocator, pattern)/Verifyselectedlabel (Selectlocator, pattern)/Verifynotselectedlabel (Selectlocator, pattern)/Waitforselectedlabel (Selectlocator, pattern)/Waitfornotselectedlabel (Selectlocator, pattern): Verifies that the text value of the selected item in the specified list conforms to the expected value.

9) Assertselectedvalue (selectorlocator, pattern)/assertnotselectedvalue (Selectorlocator, pattern)/ Verifyselectedvalue (Selectorlocator, pattern)/verifynotselectedvalue (Selectorlocator, pattern)/ Waitforselectedvalue (Selectorlocator, pattern)/waitfornotselectedvalue (Selectorlocator, pattern): Verifies that the true value of the selected item in the specified list conforms to the expected value.

Assertselectoptions (Selectlocator, pattern)/assertnotselectoptions (Selectlocator, pattern)/ Verifyselectoptions (Selectlocator, pattern)/verifynotselectoptions (Selectlocator, pattern)/waitforselectoptions ( Selectlocator, pattern)/waitfornotselectoptions (Selectlocator, pattern): Verifies that the text of all options in the specified list conforms to the expected value.

One) asserttable (tablecelladdress, pattern)/assertnottable (tablecelladdress, pattern)/verifytable (tablecelladdress , pattern)/verifynottable (tablecelladdress, pattern)/waitfortable (tablecelladdress, pattern)/waitfornottable ( Tablecelladdress, pattern): Verifies that the value of a cell in a table matches the expected value.

Assertattribute (Attributelocator, pattern)/Assertnotattribute (Attributelocator, pattern)/Verifyattribute ( Attributelocator, pattern)/Verifynotattribute (Attributelocator, pattern)/Waitforattribute (Attributelocator, pattern)/Waitfornotattribute (Attributelocator, pattern): Verifies that the value of the specified property conforms to the expected value.

Asserttextpresent (pattern)/assertnottextpresent (pattern)/verifytextpresent (pattern)/verifynottextpresent ( pattern)/waitfortextpresent (pattern)/waitfornottextpresent: Verifies that the specified text appears in the page.

Assertelementpresent (Locator)/assertnotelementpresent (Locator)/verifyelementpresent (Locator)/ Verifynotelementpresent (Locator)/waitforelementpresent (Locator)/Waitfornotelementpresent (Locator): Verifies that the specified element exists on the page.

Assertvisible (Locator)/assertnotvisible (Locator)/verifyvisible (Locator)/verifynotvisible (Locator)/ Waitforvisible (Locator)/waitfornotvisible (Locator): verifies whether the specified element is displayed in the page.


4. Target and value


4.1 Identifier positioning

Target is required for most command, and is primarily used to identify elements of a Web page in the form of "anchor type = positional value". In many cases, the positioning type can be omitted, and depending on the usage scenario, the targeting type is different.

Identifier is the most common way to locate an element, and it will be the default if there is no location type. If you use this positioning method, the IDE first looks for the first page element with an id attribute equal to the anchor value, and if it is not found, it looks for the first page element with the name attribute equal to the anchor value, and if it is not found, the location fails.


4.2 ID and name locator

The ID and name positioning are more granular and more specific than the identifier positioning method. You can use this method if you already know the ID or name of an element. If you have more than one element with the same name property, you can use a filter to further refine the positioning, and the default filter type is value (that is, the Value property), such as "Name=username value=admin".


4.3 XPath positioning

XPath expressions are used to locate nodes in an XML document, and HTML can be seen as an implementation of XML. XPath positioning is richer than the previous use of the ID or Name property, but more dependent on the position of the element in the page.


4.4 Link Text Positioning

By linking text positioning, you can navigate to the corresponding link by simply providing the link text, and if there are multiple links with the same text, the first link, such as "Link=click", will be matched.


4.5 Dom Positioning

The DOM is used to describe HTML documents that can be accessed through JavaScript. The positioning method requires JavaScript to calculate the position of the element on the page, using the graduated symbol "." Elements can be easily positioned, such as "Dom=document.getelementbyid (' username ')".


4.6 CSS Positioning

CSS is a language that describes how HTML and XML documents are displayed. CSS uses selectors to bind style attributes to elements in a document, which can also be used in selenium as an additional positioning method, such as "css= #loginForm input:username".


4.7 Implicit positioning

You can omit the "Anchor type =" section in the target expression when you encounter the following conditions.

1) When the target expression does not specify an explicit targeting method, identifier is used by default.

2) If the target expression begins with "//", the XPath is used for positioning.

3) If the target expression starts with "document", the DOM is used for positioning.


4.8 String with variable

Value can be either a string with a variable or a string with JavaScript in addition to plain text. For example, value values are made up of two variables: FirstName and LastName, so you can use "full name is: $ (firstName) $ (lastName)".


4.9 string with JavaScript

In the same example, if the value is still composed of firstName and LastName and you need to convert the variable to uppercase, you can use "Javascript{full name is:" + storedvars["FirstName"]. toUpperCase () + "" + storedvars["LastName"].touppercase ()}


5. Logging and exporting


5.1 Logs

On the Selenium IDE interface, there is also a dialog box that includes the log, Reference, Ui-element, and Rollup options, as follows:

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M00/5D/0E/wKiom1Ufq06zUsanAAA5N6nofkY303.jpg "title=" Selenium.jpg "alt=" Wkiom1ufq06zusanaaa5n6nofky303.jpg "/>

The most common is the log and Reference tab, which is used to display information when the test is performed, which is helpful for debugging, clicking the Info button to filter the log, and clicking the Clear button will clear all the logs. The References tab is used to display the help documentation for the currently used command, such as selecting the type in the test Steps tab, as follows:

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M02/5D/0E/wKiom1UfrBTDfWfbAADYTmfsC5s669.jpg "title=" Selenium.jpg "alt=" Wkiom1ufrbtdfwfbaadytmfsc5s669.jpg "/>


5.2 Command Export

In the test steps list, you can copy a command, the default is to copy the HTML source, but you can also set up, copy it to other types of source code, for reference. Simply select "Options->clipboardformat" in the menu and select the corresponding language and selenium version, as shown below:

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M00/5D/0E/wKiom1UfrQ3jkbGJAANsgAJHfrU443.jpg "title=" Selenium.jpg "alt=" Wkiom1ufrq3jkbgjaansgajhfru443.jpg "/>

You can also export the entire test case to other code by selecting "File->exporttest case as" or "file->export test Suite as" in the menu and selecting the corresponding language and selenium version, as shown below:

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M00/5D/0E/wKiom1UfrgmAgFi2AANWW-1JVqM443.jpg "title=" Selenium.jpg "alt=" Wkiom1ufrgmagfi2aanww-1jvqm443.jpg "/>



This article from "Qing Feng Notes" blog, declined to reprint!

[Selenium] Basic use

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.