Landlord Original, Welcome to learn and exchange, code word is not easy, reproduced please indicate the source, thank you.
When you use selenium webdriver for element positioning, you typically use the Findelement or Findelements method to position the element with the element handle returned by the by class. Among them, by the common positioning method of eight kinds, are described below respectively.
1. By.name ()
Suppose we want to test the source of the page as follows:
<id= "GBQFBA" aria-label= "Google Search" name= " BTNK " class=" GBQFBA "><id=" GBQFSA " >Google Search</span></button>
When we want to use the Name property to refer to this button and click on it, the code is as follows:
1 Public classSearchbuttonbyname {2 Public Static voidMain (string[] args) {3Webdriver Driver =Newfirefoxdriver ();4Driver.get ("http://www.forexample.com");5Webelement searchbox = driver.findelement (By.name ("BTNK"));6 Searchbox.click ();7 }8}
View Code
2. By.id ()
Page source code is as follows:
1 < ID= "GBQFBA" aria-label= "Google Search" name= "BTNK" class = "GBQFBA" >< ID= "GBQFSA">Google Search</span ></button>
To refer to the button and click on it, the code is as follows:
1 Public classSearchbuttonbyid {2 3 Public Static voidMain (string[] args) {4 5Webdriver Driver =Newfirefoxdriver ();6 7Driver.get ("http://www.forexample.com");8 9Webelement searchbox = driver.findelement (By.id ("GBQFBA"));Ten One Searchbox.click (); A - } - the}
3. By.tagname ()
The method can find the element by its label name. The difference between this method and the previous two methods is that this method usually searches for more than one element, so it is generally recommended to use the Findelements method together. For example, if we want to find the number of buttons on the page now, we can use the button this tagname to find, the code is as follows:
Public class searchpagebytagname{ publicstaticvoid main (string[] args) { New firefoxdriver (); Driver.get ("http://www.forexample.com"); List<WebElement> buttons = driver.findelements (By.tagname ("button")); System.out.println (Buttons.size ()); // print out the number of buttons }}
In addition, when using the TagName method to locate, there is also a place to note that there are usually some HTML elements of the tagname is the same, as shown in (1).
Figure (1)
As we can see, the element labels for the radio box, check box, text box, and password box are input, and tagname cannot get exactly the element we want, we need to combine the type attribute to filter out the element we want. The sample code is as follows:
1 Public classsearchelementsbytagname{2 3 Public Static voidMain (string[] args) {4 5Webdriver Driver =Newfirefoxdriver ();6 7Driver.get ("http://www.forexample.com");8 9list<webelement> allinputs = driver.findelements (by.tagname ("Input"));Ten One //print only values for all text boxes A - for(webelement e:allinputs) { - the if(E.getattribute ("type"). Equals ("text")) { - -System.out.println (E.gettext (). toString ());//print out the values in each text box - + } - + } A at } - -}
4. By.classname ()
The ClassName property is a method of element lookup using the pseudo-class name referenced by the element's CSS style sheet. For any HTML page element, the General programmer or page designer gives the element a style attribute directly or uses the pseudo-class in the CSS file to define the element style, which makes the element more aesthetically pleasing to display on the page. The general CSS style sheet might look like this:
1 . ButtonStyle { 2 3 width: 50px; 4 5 height: 50px ; 6 7 Border-radius: 50%; 8 9 margin: 0% 2%; Ten One}
Once defined, you can refer to the above defined style in the page element as follows:
1 < name= "Samplebtnname" ID= "Samplebtnid" class= " ButtonStyle ">I ' m button</button>
If we want to find the button and manipulate it through the ClassName property at this point, we can use the ClassName property with the following code:
1 Public classsearchelementsbyclassname{2 3 Public Static voidMain (string[] args) {4 5Webdriver Driver =Newfirefoxdriver ();6 7Driver.get ("http://www.forexample.com");8 9Webelement searchbox = driver.findelement (By.classname ("ButtonStyle"));Ten OneSearchbox.sendkeys ("Hello, World"); A - } - the}
Note: When using classname for element positioning, it is sometimes encountered when an element specifies a "compound style" for several class attribute values, such as the following Button:<button id= "J_sidebar_login" class= "btn Btn_big Btn_submit "type=" submit "> Login </button>. This button element specifies three different CSS pseudo-class masterpieces as its style attribute values, which must be positioned in conjunction with the Cssselector method described later, with detailed examples later.
5. By.linktext ()
This method is more straightforward, that is, the text information on hypertext links to locate elements, which is generally used to locate the Hypertext link on the page. Usually a hypertext link looks like this:
1 < href= "/intl/en/about.html">about Google</a>
When we locate this element, we can do it using the following code:
1 Public classsearchelementsbylinktext{2 3 Public Static voidMain (string[] args) {4 5Webdriver Driver =Newfirefoxdriver ();6 7Driver.get ("http://www.forexample.com");8 9Webelement Aboutlink = driver.findelement (By.linktext ("About Google"));Ten One Aboutlink.click (); A - } - the}
6. By.partiallinktext ()
This method is an extension of the previous method. You can use this method to match some of the linked text when you don't know exactly what text is on the hyperlink or just want to match it with some keywords. The code is as follows:
1 Public classsearchelementsbypartiallinktext{2 3 Public Static voidMain (string[] args) {4 5Webdriver Driver =Newfirefoxdriver ();6 7Driver.get ("http://www.forexample.com");8 9Webelement Aboutlink = driver.findelement (By.partiallinktext ("about"));Ten One Aboutlink.click (); A - } - the}
Note: When you use this method to locate, the problem that may arise is that when more than one hyperlink in your page contains about, the Findelement method only returns the first found element, and does not return all eligible elements. If you want to get all the eligible elements, you can only use the Findelements method.
7. By.xpath ()
This method is a very powerful way to find elements that can be used to locate almost any element on a page. Before we formally start using XPath for positioning, let's first understand what XPath is. XPath is the abbreviation for XML path, because the HTML document itself is a standard XML page, so we can use XPath syntax to locate page elements.
Suppose we now take the HTML code shown in figure (2) as an example, to refer to the corresponding object, the XPath syntax is as follows:
Figure (2)
Absolute path notation (only one), written as follows:
Reference the form element on the page (that is, line 3rd in the source code):/html/body/form[1]
Note: 1. The XPath absolute path of the element can be queried directly by Firebug. 2. It is generally not recommended to use absolute path notation, because once the page structure changes, the path is also invalidated and must be re-written. 3. The absolute path begins with a single/number, and the following relative path begins with //.
Here is a reference to the relative path:
Find page root element://
Find all input elements on a page://input
Find all the input tags on the page that are contained within the form element://form[1]/input
Find the first FORM element on a page://form[1]
Find the form element with ID loginform on the page://form[@id = ' loginform ')
The input element on the lookup page with the name attribute username://input[@name = ' username ')
Find the first INPUT element under a FORM element with ID loginform on the page://form[@id = ' loginform ']/input[1]
The lookup page has the Name property of Contiune and the type attribute is the INPUT element of the button://input[@name = ' Continue ' [@type = ' button ']
Find the 4th INPUT element under the form element with ID loginform on the page://form[@id = ' loginform ']/input[4]
XPath function is very powerful, so can also be written more complex, such as the following figure (3) of the HTML source code.
Figure (3)
What if we want to refer to the INPUT element with ID "J_password" now? We can write like this:
webelement password = driver.findelement (By.xpath ("//*[@id = ' J_login_form ']/dl/dt/input[@id = ' J_password ']"));
Can also be written as:
webelement password = driver.findelement (By.xpath ("//*[@id = ' J_login_form ']/*/*/input[@id = ' J_password ']"));
Here's an explanation, where//*[@id = ' j_login_form ') This paragraph refers to finding any element under the root element with any ID of j_login_form, which is equivalent to referencing the form element. The following path must be written down according to the source level. In the code shown in figure (3), the INPUT element we are looking for is contained within a DT tag, and DT is included in the DL tag, so it must be written on the DL and DT two layers before the input layer. Of course, we can omit the specific tag name with the * number, but the hierarchy of elements must be reflected, such as we can not write//*[@id = ' J_login_form ']/input[@id = ' J_password '), this will definitely be an error.
Finally, with respect to XPath's positioning method, Webdriver will scan all elements of the entire page to locate the elements we need, so this is a very time-consuming operation, and if you use XPath for element positioning in your script, your script execution will be much slower, So please use it with caution.
8. By.cssselector ()
Cssselector This element is located in a similar way to XPath, but executes faster, and the support of various browsers is quite in place, so the function is quite powerful.
Here are some common ways to locate Cssselector:
Locate the div element with ID flrs, which can be written as: #flrs Note://div[equivalent to the XPath syntax @id = ' Flrs ')
Locate the A element under FLRS, which can be written as #flrs > a note://div[equivalent to the XPath syntax @id = ' Flrs ']/a
Locate an element with an HREF attribute value of/forexample/about.html under ID flrs, which can be written as: #flrs > a[href= "/forexample/about.html"]
If you need to specify multiple property values, you can add them one after the other, such as #flrs > input[name= "username"][type= "text"].
After understanding the basic syntax, let's try to use the Cssselector method to refer to the input object selected in Figure (3), the code is as follows:
webelement password = driver.findelement (By.cssselector ("#J_login_form >dl>dt>input[id= ' J_password ']");
Also must pay attention to the hierarchical relationship, this cannot be omitted.
Cssselector is also useful for locating elements that use a composite style sheet, as previously mentioned in the 4th way classname. Now let's see how to use Cssselector to refer to the button mentioned in the 4th way. The button code is as follows:
class= "btn btn_big btn_submit" type= "submit" > Login </button>
The Cssselector reference element code is as follows:
Driver.findelement (By.cssselector ("Button.btn.btn_big.btn_submit"))
。 This makes it easy to refer to elements that use a composite style.
In addition, Cssselector also has some advanced usage, if skilled can be more convenient to help us locate elements, such as we can use ^ to match a prefix, $ to match a suffix, * to match any character. For example:
Matches an id attribute, and the id attribute is a hyperlink element that begins with "Id_prefix_": a[id^= ' id_prefix_ ']
Match an id attribute, and the id attribute is the hyperlink element ending with "_id_sufix": a[id$= ' _id_sufix ']
Match a hyperlink element that has an id attribute and an id attribute that contains the "Id_pattern" character: a[id*= ' Id_pattern ')
Finally, a summary of the various ways to choose the time should be how to choose:
1. When the page element has an id attribute, it is best to use ID to locate it. However, because many programmers in the real project actually write code that is not canonical, and will lack many standard attributes, then only choose other location method.
2. XPath is strong, but the positioning performance is not very good, so try to use less. If you do not have a few elements that are not well positioned, you can choose XPath or cssselector.
3. Consider using tagname or name when you want to locate the same element for a group of elements.
4. When a link needs to be located, consider Linktext or Partiallinktext mode.
Resources:
"Selenium Webdriver Practical Guide"
Https://saucelabs.com/resources/selenium/css-selectors
Eight common ways to locate Selenium webdriver elements