행위

Selenium xpath

DB CAFE

Dbcafe (토론 | 기여)님의 2021년 5월 27일 (목) 11:20 판
thumb_up 추천메뉴 바로가기


1 Xpath 개요[편집]

Selenium WebDriver를 사용하여 웹 애플리케이션을 자동화 할 때 가장 어려운 작업 중 하나는 웹 요소를 찾는 것입니다.

Selenium WebDriver는 다양한 로케이터 전략을 지원합니다.

  1. Id
  2. CSS
  3. XPATH
  4. Class Name
  5. Name
  6. Tag Name
  7. Links Text
  8. Partial Links Text

Among all the locator strategies Id is the best locator, as a standard, Id is unique in a web page. But in real life nothing is perfect. In real life scenario you will hardly get Id in every element. Here comes the need for the rest of the locator strategies.

Keeping this in mind I am going to write a series of blogs regarding locator strategies. In this blog I will try to focus on XPath Basics.

1.1 XPath[편집]

  1. XML 경로 언어 인 XPath는 XML 문서에서 노드를 선택하기위한 쿼리 언어.
  2. XPath 언어는 XML 문서의 트리 표현 (계층 적)을 기반으로하며 다양한 기준에 따라 노드를 선택하여 트리를 탐색 할 수있는 기능을 제공.
  3. XPath로 요소를 찾는 것은 많은 유연성으로 매우 잘 작동합니다.
  4. 느린 성능으로 인해 가장 선호되지 않는 로케이터 전략.
  5. XPath와 CSS의 중요한 차이점 중 하나는 XPath를 사용하여 DOM 계층 구조에서 요소를 앞뒤로 검색 할 수 있지만 CSS는 순방향으로 만 작동한다는 것입니다.
    XPath를 사용하여 자식 요소를 사용하여 부모 요소를 찾을 수 있음을 의미합니다.
  6. XPath는 대소 문자를 구분하는 언어입니다.
  7. HTML 페이지는 DOM에서 XHTML 문서로 표시되고 요소를 찾기 위해 Selenium WebDriver에서 사용되므로 모든 주요 브라우저는 XPath를 지원.
  8. XPath를 찾는 데 사용할 수있는 여러 도구가 있습니다. Firefox 브라우저 Firebug 및 XPath Checker 추가 기능 및 Chrome XPath Helper 및 Toggle XPather의 경우.

XPath 표현식 :


XPath expression generally defines a pattern in order to select a set of nodes. XPath uses path expression to select nodes or list of nodes from an XML/html document. This path can be of two type:

Absolute Path Relative Path Absolute path means to specify every single node to select a node inside a hierarchical document. It always starts from root node. Here is an example:

/html/body/div[2]/div/div[4]/div/ul/li[3]/a/span

It is relatively faster then Relative path. But the XPath expression may be very lengthy. More over each of those nested relationships will need to be present 100% of the time, or the locator will not work. For these reasons use of Relative XPath expressions are encouraged.

In Relative XPath expression you can start from the node of your choice. The above absolute path can be written in the following relative path:

//div[@id='navigation']/ul/li[3]/a/span

In this blog, my prime focus will be to demonstrate the Relative XPath. Expression: “/” & “//” You may notice from above two example that I sometime used “/” and sometimes “//”. This is a very important point to understand. A single slash ‘/’ anywhere in XPath signifies to look for the element immediately inside its parent element. A double slash ‘//’ signifies to look for any child or any grand-child (descendant) element inside the parent element. In the following two example it will be more clear.

.//div[@id='products']/a/img

Look carefully in the above example, here I am trying to find an image tag from html document, which is the child of tag ‘a’. And tag a is the child of div tag. The same image tag can be found by:

.//div[@id='products']//img

Here I am trying to find an image tag which is the descendant of tag div.

Expression: “.” & “..” You may have noticed that in every example I have used “.”. This is used to specify current node in XPath. “..” is used to move one step up in the document tree, that is it will find the parent of current node. An example will make it more clear:

.//div[@id='products']/..

This expression will find the parent node of the current node.

Expression: “@” “@” is used to select attribute in the document tree. In the above example I specify attribute id with “@” and the value products inside ‘ ’.

Expression: “*” XPath support wildcard like “*”. Sometimes it is of much use to find a Relative path. Let’s see an example:

.//*[text()='Home']

This wildcard can be used in place of attribute too.

.//a[@*='Home']

In this case I am trying to find an element which has an attribute with value ‘home’. In this case I don’t care about the attribute name. You will not use it very often. But its good keep it as an option. Here in this section I am going to illustrate to most handy trick of XPath. Most of the times you will face issues when the locator’s properties are dynamically generated. And now a days petty much all the web application follows this strategy. Here comes the real challenge to deal with all the issue. Following section will give you concept about how to deal with such situations.

Read the following section carefully and try to understand and implement these tricks.

Expression using keyword “contains”: “contains()” is a function that take two arguments, attribute name and attribute value. Let’s see an example:

.//div[contains(@id, 'search')]

Here I am finding a div tag which contains an attribute named ‘id’, in which the value contains ‘search’. It doesn’t need to be exactly the ‘search’ but the pattern needs to match. Function ‘contains()’ match attribute name with value by matching pattern. Here is another use of function ‘contains()’:

.//span[contains(text(), 'Hot')]

This expression finds a span tag which contains ‘Hot’ as text in it. Expression using keyword “text()”: In previous example you saw, I used function ‘text()’. Let’s have a deeper look into function ‘text()’. It will find out a specific tag which has specific text in it. Here is an example:

.//span[text()= 'Home']

As I said this expression will find a span tag with text ‘Home’.

Expression using keyword “starts-with()”: Like function ‘contains()’, ‘starts-with()’ also take two arguments, attribute name and attribute value. Let’s look it in an example:

.//div[starts-with(@class, 'width')]

Here I am trying to find a div tag where there is an attribute ‘class’ that starts with pattern ‘width’. This function also find element by matching pattern. Another example:

.//span[starts-with(text(), 'Gift')]

As you saw earlier in ‘contains()’ function I used ‘text()’ function to find text inside that tag. That can be also done with function ‘starts-with()’ .

Conclusion: In this blog, I focused on a number of the tricks and techniques that you will use daily as a Test Automation Engineer. There is no end of learning. You can learn more about XPath. Next time I will try to focus on some advance topic in XPath. Till then Practice…