Locating UI Elements
By Link Text
Find the link element with matching visible text.
Example of how to find an element that looks like this:
<a href="http://www.google.com/search?q=cheese">cheese</a>>
WebElement cheese = driver.findElement(By.linkText("cheese"));
By Partial Link Text
Find the link element with partial matching visible text.
Example of how to find an element that looks like this:
<a href="http://www.google.com/search?q=cheese">search for cheese</a>>
WebElement cheese = driver.findElement(By.partialLinkText("cheese"));
By CSS
Like the name implies it is a locator strategy by css. Native browser support is used by default, so please refer to w3c css selectors for a list of generally available css selectors. If a browser does not have native support for css queries, then Sizzle is used. IE 6,7 and FF3.0 currently use Sizzle as the css query engine.
Beware that not all browsers were created equal, some css that might work in one version may not work in another.
Example of to find the cheese below:
<div id="food"><span class="dairy">milk</span><span class="dairy aged">cheese</span></div>
WebElement cheese = driver.findElement(By.cssSelector("#food span.dairy.aged"));
By XPATH
At a high level, WebDriver uses a browser’s native XPath capabilities wherever possible. On those browsers that don’t have native XPath support, we have provided our own implementation. This can lead to some unexpected behaviour unless you are aware of the differences in the various xpath engines.
Driver | Tag and Attribute Name | Attribute Values | Native XPath Support |
---|---|---|---|
HtmlUnit Driver | Lower-cased | As they appear in the HTML | Yes |
Internet Explorer Driver | Lower-cased | As they appear in the HTML | No |
Firefox Driver | Case insensitive | As they appear in the HTML | Yes |
This is a little abstract, so for the following piece of HTML:
<input type="text" name="example" />
<INPUT type="text" name="other" />
List<WebElement> inputs = driver.findElements(By.xpath("//input"));
The following number of matches will be found
XPath expression | HtmlUnit Driver | Firefox Driver | Internet Explorer Driver |
---|---|---|---|
//input | 1 (“example”) | 2 | 2 |
//INPUT | 0 | 2 | 0 |
Sometimes HTML elements do not need attributes to be explicitly declared because they will default to known values. For example, the “input” tag does not require the “type” attribute because it defaults to “text”. The rule of thumb when using xpath in WebDriver is that you should not expect to be able to match against these implicit attributes.
No comments:
Post a Comment