Selenium How webdriver elements are positioned
The main thing is by class
1, By.name ()
##
The HTML code is as follows:
<button id="gbqfba" aria-label="Google Search" name="btnK" class="gbqfba"><span id="gbqfsa">Google Search</span></button>
When you use the Name property to refer to the button and click on it, the code is as follows:
public class SearchButtonByName { public static void main(String[] args){ WebDriver driver = new FirefoxDriver(); driver.get("http://www.forexample.com"); WebElement searchBox = driver.findElement(By.name("btnK")); searchBox.click(); }}
2, By.id ()
The HTML code is as follows:
<button id="gbqfba" aria-label="Google Search" name="btnK" class="gbqfba"><span id="gbqfsa">Google Search</span></button>
To use the id attribute to refer to this button and click on it, the code is as follows:
public class Searchbuttonbyid {
public static void main(String[] args){ WebDriver driver = new FirefoxDriver(); driver.get("http://www.forexample.com"); WebElement searchBox = driver.findElement(By.id("gbqfba")); searchBox.click(); }}
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 FirefoxDriver(); driver.get("http://www.forexample.com"); List<WebElement> buttons = driver.findElements(By.tagName("button")); System.out.println(buttons.size()); //打印出button的个数 }}
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).
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:
public class SearchElementsByTagName{ public static void main(String[] args){ WebDriver driver = new FirefoxDriver(); driver.get("http://www.forexample.com"); List<WebElement> allInputs = driver.findElements(By.tagName("input")); //只打印所有文本框的值 for(WebElement e: allInputs){ if (e.getAttribute(“type”).equals(“text”)){ System.out.println(e.getText().toString()); //打印出每个文本框里的值 } } }}
4, By.classnmae ()
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:
.buttonStyle{ width: 50px; height: 50px; border-radius: 50%; margin: 0% 2%;}
Once defined, you can refer to the above defined style in the page element as follows:
<button name="sampleBtnName" id="sampleBtnId" class="buttonStyle">I‘m Button</button>
To find the button and manipulate it through the ClassName property, you can use the ClassName property, which is the following code:
public class SearchElementsByClassName{ public static void main(String[] args){ WebDriver driver = new FirefoxDriver(); driver.get("http://www.forexample.com"); WebElement searchBox = driver.findElement(By.className("buttonStyle")); searchBox.sendKeys("Hello, world"); }}
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: Login. 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:
<a href="/intl/en/about.html">About Google</a>
When locating this element, you can do this using the following code:
public class SearchElementsByLinkText{ public static void main(String[] args){ WebDriver driver = new FirefoxDriver(); driver.get("http://www.forexample.com"); WebElement aboutLink = driver.findElement(By.linkText("About Google")); aboutLink.click(); }}
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:
public class SearchElementsByPartialLinkText{ public static void main(String[] args){ WebDriver driver = new FirefoxDriver(); driver.get("http://www.forexample.com"); WebElement aboutLink = driver.findElement(By.partialLinkText("About")); aboutLink.click(); }}
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:
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.
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‘]"));
Or:
WebElement password = driver.findElement(By.xpath("//*[@id=‘J_login_form‘]/*/*/input[@id=‘J_password‘]"));
Explain here, where//[@id = ' j_login_form '] this paragraph refers to finding any element under the root element with any ID 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 label name, but the hierarchy of elements must be reflected, such as we can not write//*[@id = ' J_login_form ']/input[@id = ' J_password '), this will certainly 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:
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.
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:
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:
driver.findElement(By.xpath(“//*[text()=’退出’]));
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
driver.findElement(By.xpath(“//a[contains(text(), ’退出’)]));
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">登录</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:
When the page element has an id attribute, it is best to use the 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.
XPath is tough, 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.
Consider using tagname or name when you want to locate the same element for a group of elements.
When there is a link that needs to be positioned, consider linktext or Partiallinktext mode.
Resources:
"Selenium Webdriver Practical Guide"
Https://saucelabs.com/resources/selenium/css-selectors
Selenium How webdriver elements are positioned