您的位置:首页 > 其它

How to Locate Web Elements with Selenium WebDriver?

2014-01-02 16:43 387 查看
In order to write UI tests with Selenium WebDriver you need to be able to identify web page elements fast and in an accurate way. You don’t want to revisit these selectors very often so you must choose the right selector from the beginning.

There are some browser tools that you can use in order to identify web elements in the DOM easier. These are:

Firebug for Firefox
Google Developer Tools for Chrome
Web Inspector for Safari

Selenium WebDriver API supports different possibilities to identify elements: by ID, by CLASS, by NAME, by CSS selector, by XPath, by TAG name. Also you define your custom selector in order to interact with the elements.

It’s always a good practice to assign unique IDs to elements, also names and classes in order to be more usable for automatic UI tests. If that is not possible you’ll need to use advanced or XPath selector to interact with those elements. The most popular selectors
are the CSS selectors due to performance and simplicity reasons.

To inspect an element you just have to open the desired web page, right-click the desired element and click on Inspect Element. A new panel will open showing the desired element. Also you can inspect other elements by clicking on the cursor in the top left
side of the Developer Tools or Firebug panels and hovering page elements.

Locating Elements with Selenium WebDriver, findElement() method returns and WebElement and findElements() returns a list of WebElements.

1. By ID:

2. By CLASS:

3. By NAME:

4. By TAGNAME:

5. By CSS Selector:

6. By Link:

7. By XPath:

Let’s get a HTML snippet code and see how can we use these Selenium WebDriver selectors in order to identify the desired elements:

Let’s get some WebElements from the above HTML code snippet:

or

or

Locate link elements with findElements() method from the HTML snipped

Locate link elements from the HTML snipped:

How to find a link with Selenium WebDriver API by full text:

How to find a link with Selenium WebDriver API by partial text:

Locate elements by HTML Tag Name:

Locate elements by CSS Selectors

or

or

Performing partial match on attribute values

Finding elements with XPATH

Absolute path

Relative path

Finding elements using index

Finding elements using attributes values with XPath

XPATH

Starting with:

Ending with:

Containing

Locating table rows and cells

Using jQuery selectors

Locate all the Checkbox which are checked by calling jQuery find() method.

find() method returns elements in array

Refer: https://loadfocus.com/blog/2013/09/how-to-locate-web-elements-with-selenium-webdriver/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: