Friday, March 17, 2017

Selenium WebDriver - How to Identify Web Elements Using Selenium XPath (Contains Method)

The XML path language (XPath) is a language that we can use for investigating specific nodes of an XML document based on specific search criteria.

Selenium WebDriver supports the XML path language as a strategy to locate elements using flexible XPath queries, this fact is very important, because all the major browsers (Firefox, IE and chrome) support it.
תוצאת תמונה עבור ‪selenium webdriver xpath contains‬‏

Partial match on element attribute values

Sometimes, you will work with different web applications that creating the element attribute values dynamically, therefore you cannot use a static attribute values that may change on every test execution, to overcome this issue XPath provides another effective way to locate elements based on a partial part of the attribute value.

The Contains method

The contains method, determines if the attribute value contains the search string that we searched for, in the locator.


<input type="text" value="" size="30" name="name" id="ContactForm1_contact-form-name" class="contact-form-name">

In the following code, we will query the element with only partial part of its id:

Full ID: "ContactForm1_contact-form-name":

WebElement = Firefox.FindElement(By. XPath("//input[contains(@id,'-name')]"));

Following the previous example, we can do the same thing with the "Starts with" function, but currently we will examine the beginning of the attribute value.

WebElement = Firefox.FindElement(By.XPath("//input[starts-with(@id,'ContactForm1)]"));

Following the previous example, we can do the same thing with the "Ends With" function, but a currently we will examine the End of the attribute value.

WebElement = Firefox.FindElement(By.XPath("//input[ends-with(@id,'form-name)]"));

No comments:

Post a Comment

My Presentations