Eight common ways to locate Selenium webdriver elements

Source: Internet
Author: User
Tags tagname xpath

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:

<button id= "GBQFBA" aria-label= "Google Search" name= "BTNK" class= "GBQFBA" ><span 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 class Searchbuttonbyname {2 public         static void Main (string[] args) {3                webdriver driver = new Firefoxdriver (); 4                driver.get ("http://www.forexample.com"); 5                webelement searchbox = driver.findelement (By.name ("BTNK")) ; 6                Searchbox.click (); 7         }8}
2. By.id ()
1 public class Searchbuttonbyid {2  3 public         static void Main (string[] args) {4  5             webdriver driver = new F Irefoxdriver (); 6  7             driver.get ("http://www.forexample.com"); 8  9             webelement searchbox = driver.findelement (By.id (" GBQFBA "));             Searchbox.click ();         }14 15}

3. By.tagname ()

The method can find the element by its tag 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 out how many buttons are on the page, we can use the button tagname to find the code as follows:

public class searchpagebytagname{public static void Main (string[] args) {Webdriver Driver = new Firefoxdri            Ver ();            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 for positioning, there is also a place to note, usually some HTML elements of the tagname are the same

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 class searchelementsbytagname{2 3 public static void main (string[] args) {4 5 Webdriver Dr Iver = new Firefoxdriver (); 6 7 driver.get ("http://www.forexample.com"); 8 9 List<webelement> allinputs = driver.findelements (by.tagname ("input")); 10 11//Print all text boxes only The value is 16 for (Webelement e:allinputs) {if (E.getattribute ("type"). Equals ("text")) {17 System.out.println (E.gettext (). toString ()); Print out the values in each text box 18 19}20 21}22 23}24 25}

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%;10 11}

Once defined, you can refer to the above defined style in the page element as follows:

1 <button 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 class searchelementsbyclassname{2  3 public     static void Main (string[] args) {4  5         Webdriver Driver = new Firefoxdriver (); 6  7         driver.get ("http://www.forexample.com"); 8  9         webelement searchbox =  driver.findelement ( By.classname ("ButtonStyle"));         Searchbox.sendkeys ("Hello, World");     }14 15}

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 <a href= "/intl/en/about.html" >about google</a>

When we locate this element, we can do it using the following code:

1 public class searchelementsbylinktext{2  3 public     static void Main (string[] args) {4  5         Webdriver Driver = new Firefoxdriver (); 6  7         driver.get ("http://www.forexample.com"); 8  9         webelement aboutlink = driver.findelement ( By.linktext ("About Google");         Aboutlink.click ();     }14 15}

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 class searchelementsbypartiallinktext{2  3 public     static void Main (string[] args) {4  5         Webdriver Driver = new Firefoxdriver (); 6  7         driver.get ("http://www.forexample.com"); 8  9         webelement aboutlink = driver.findelement ( By.partiallinktext ("about"));         Aboutlink.click ();     }14 15}

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 is represented by a single/number, and the following relative path is represented by//, which is very important. Another thing to say is that when the path of the XPath starts with/begins, the XPath parsing engine is parsed from the root node of the document. When the XPath path starts with//, it means that the XPath engine parses from any conforming element node of the document. When/appears in the XPath path, it means looking for the parent node's immediate child node, when//appears in the XPath path, to look for any child node under the parent node that meets any criteria, no matter how many levels are nested (these are examples below, you can refer to the experiment). Understanding this principle, you can understand that the XPath path can be the absolute path and relative path mixed together to represent, want to play how to play.

Here is a reference to the relative path:

Find page root element://

Find all input elements on a page://input

Finds the direct child INPUT element within the first FORM element on the page (that is, only the next INPUT element of the form element, using an absolute path representation, single/number)://form[1]/input

Finds all child input elements within the first FORM element on the page (as long as input within the form element is counted, regardless of how many other tags are nested, using relative paths, double//number)://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.

All of this is based on the positioning of the exact element attribute in XPath, in fact XPath can also be used as the positioning artifact for fuzzy matching. For example, the following figure (4) shows the code:

Figure (4)

In this code, "exit" This hyperlink, there is no standard ID element, only a rel and href, not very well positioned. We can use some of the XPath fuzzy matching pattern to locate it, there are three main ways, such as the following.

A. Using the CONTAINS keyword, locate the code as follows:

1 driver.findelement (By.xpath ("//a[contains (@href, ' logout ')]");

The meaning of this sentence is to find that the HREF attribute value in the page contains all the A elements of the word logout, because the href attribute of the Exit button will certainly contain logout, so this method is feasible and often used. Where @ can be followed by any property name of the element.

B. Using Start-with, locate the code as follows:

1 driver.findelement (By.xpath ("//a[starts-with (@rel, ' Nofo ')]);

The meaning of this sentence is to look for the A element with the Rel attribute beginning with Nofo. Where the rel after @ can be substituted for any other attribute of the element.

C. Using the text keyword, locate the code as follows:

1 driver.findelement (By.xpath ("//*[text () = ' exit ']));

This method is quite domineering. Directly find all of the exit word in the page, there is no need to know that it is a element. This method is also often used for plain text lookups.

In addition, if you know the text content of a hyperlink element, you can also use the

1 driver.findelement (By.xpath ("//a[contains () (Text (), ' exit ')]);

This is typically used when you know that some or all of the text information is displayed on a hyperlink.

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:

<button id= "J_sidebar_login" 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.






Eight common ways to locate Selenium webdriver elements

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.