행위

"Selenium xpath"의 두 판 사이의 차이

DB CAFE

(새 문서: Preface: One of the most challenging task in automating Web application using Selenium WebDriver is finding Web element. Selenium WebDriver supports a number of locator strategies- I...)
 
(Descendant XPath)
 
(같은 사용자의 중간 판 95개는 보이지 않습니다)
1번째 줄: 1번째 줄:
Preface:
+
== Xpath 개요 ==
One of the most challenging task in automating Web application using Selenium WebDriver is finding Web element. Selenium WebDriver supports a number of locator strategies-
+
Selenium WebDriver를 사용하여 웹 애플리케이션을 자동화 할 때 가장 어려운 작업 중 하나는 웹 요소를 찾는 것입니다.
 +
{{틀:고지 상자
 +
|내용= Selenium WebDriver 에서 요소(Element)를 찾는 로케이터(Locator)
 +
# Id
 +
# CSS
 +
# XPATH
 +
# Class Name
 +
# Name
 +
# Tag Name
 +
# Links Text
 +
# Partial Links Text
 +
|아이콘=filter_3
 +
}}
 +
=== XPath 란? ===
 +
{{틀:고지 상자
 +
|내용='''XPATH'''
 +
# XML 경로 언어 인 XPath는 XML 문서에서 노드를 선택하기위한 쿼리 언어.  
 +
# XPath 언어는 XML 문서의 트리 표현 (계층 적)을 기반으로하며 다양한 기준에 따라 노드를 선택하여 트리를 탐색 할 수있는 기능을 제공.
 +
# XPath로 요소를 찾는 것은 많은 유연성으로 매우 잘 작동합니다.
 +
# 느린 성능으로 인해 가장 선호되지 않는 로케이터 전략.
 +
# XPath와 CSS의 중요한 차이점 중 하나는 XPath를 사용하여 DOM 계층 구조에서 요소를 앞뒤로 검색 할 수 있지만 CSS는 순방향으로 만 작동한다는 것입니다. XPath를 사용하여 자식 요소를 사용하여 부모 요소를 찾을 수 있음을 의미합니다.
 +
# XPath는 대소 문자를 구분하는 언어입니다.
 +
# HTML 페이지는 DOM에서 XHTML 문서로 표시되고 요소를 찾기 위해 Selenium WebDriver에서 사용되므로 모든 주요 브라우저는 XPath를 지원.
 +
# XPath를 찾을때 Firefox 브라우저 Firebug 및 XPath Checker 추가 기능 및 Chrome XPath Helper 및 Toggle XPather 플러그인 사용 추천
 +
}}
  
Id
+
=== XPath 표현식 ===
CSS
+
==== 절대경로 (Absolute Path) ====
XPATH
+
{{틀:고지 상자
Class Name
+
|내용= '''절대경로'''
Name
+
# 절대 경로는 계층 문서 내에서 노드를 선택하기 위해 모든 단일 노드를 지정하는 것을 의미합니다.
Tag Name
+
# 항상 루트 노드에서 시작합니다.
Links Text
+
}}
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.
+
<source lang=c>
 +
/html/body/div[2]/div/div[4]/div/ul/li[3]/a/span
 +
</source>
  
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.
+
==== 상대경로 (Relative Path) ====
 +
{{틀:고지 상자
 +
|내용= '''상대경로'''
 +
# 상대경로 XPath 표현식은 매우 길 수 있습니다.
 +
# 중첩 된 각 관계에 대해 100% 존재해야 함. 그렇지 않으면 로케이터가 작동하지 않습니다.
 +
#: 이러한 이유로 Relative XPath 표현식을 사용하는 것이 좋습니다.
 +
# 상대 XPath 표현식에서는 선택한 노드에서 시작할 수 있습니다.
 +
# 위의 절대 경로를 다음 상대 경로에도 쓸 수 있습니다.
 +
}}
 +
<source lang=html>
 +
//div[@id='navigation']/ul/li[3]/a/span
 +
</source>
  
XPath:
+
==== 슬래쉬 “/” 와 "//" 의미 ====
XPath, the XML path language, is a query language for selecting nodes from an XML document. The XPath language is based on a tree representation(hierarchical) of the XML document, and provides the ability to navigate around the tree, selecting nodes by a variety of criteria. XPath has been adopted by a number of XML processing libraries and tools, many of which also offer CSS Selectors, another W3C standard, as a simpler alternative to XPath.
+
{{틀:고지 상자
 +
|내용= '''“/” 와 "//"'''
 +
# XPath의 어느 곳에서나 하나의 슬래시 '/'는 상위 요소 내에서 바로 요소를 찾는 것을 의미합니다.  
 +
# 이중 슬래시‘//’는 상위 요소 내에서 하위 또는 손자 (하위) 요소를 찾는 것을 나타냅니다.
 +
}}
 +
# 두가지 예시 참조
 +
# 예시 1)
 +
<source lang=html>
 +
.//div[@id='products']/a/img
 +
</source>
 +
## 'a' 태그의 하위 인 html 문서에서 이미지 태그를 찾으려고합니다.  
 +
## 그리고 a 태그는 div 태그의 자식입니다.
 +
## 동일한 img 태그는 다음에서 찾을 수 있습니다.
 +
# 예시 2)
 +
<source lang=html>
 +
.//div[@id='products']//img
 +
</source>
  
Locating elements with XPath works very well with a lot of flexibility. However, this is the least preferable locator strategy due its slow performance. One of the important differences between XPath and CSS is, with XPath we can search elements backward or forward in the DOM hierarchy while CSS works only in a forward direction. This means that with XPath we can locate a parent element using a child element. Remember XPath is a case sensitive language.
+
==== 점 “.” 와 “..” 의미 ====
  
All the major browsers support XPath as HTML pages are represented as XHTML documents in DOM and used by Selenium WebDriver for locating elements. There are a number of tools you can use to find out XPath. For Firefox browser Firebug and XPath Checker Add-on and for Chrome XPath Helper and Toggle XPather.
+
{{틀:고지 상자
XPath Expression:
+
|내용= '''“.” 와 “..”'''
 +
# "." 은 XPath에서 현재 노드를 지정하는 데 사용됩니다.
 +
# ".." 은 문서 트리에서 한 단계 위로 이동하는 데 사용됩니다.  
 +
#: 즉, 현재 노드의 부모를 찾습니다.
 +
}}
 +
# 예시)
 +
<source lang=html>
 +
.//div[@id='products']/..
 +
</source>
 +
* 위 표현식은 현재 노드의 부모 노드를 찾습니다.
  
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:
+
==== "@”의 의미 ====
 +
{{틀:고지 상자
 +
|내용= '''“@”'''
 +
# "@"는 문서 트리에서 속성을 선택하는 데 사용됩니다.
 +
# 위의 예시에서 "@"로 속성 ID를 지정하고‘’안에 값 'products' 지정 함.
 +
}}
  
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:
+
|내용= '''“ * ”'''
 +
# XPath는 "*"와 같은 와일드 카드를 지원합니다.  
 +
#: 때로는 상대 경로를 찾는 데 많이 유용합니다.  
 +
}}
  
/html/body/div[2]/div/div[4]/div/ul/li[3]/a/span
+
# 예시 )
 +
<source lang=html>
 +
.//*[text()='Home']
 +
</source>
 +
<source lang=html>
 +
.//a[@*='Home']
 +
</source>
 +
* 이 경우 값이 'home'인 속성을 가진 요소를 찾으려고합니다.
 +
* 이 경우 속성 이름은 신경 쓰지 않습니다.
  
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:
+
==== 형제/자식/조상 요소 찾기  ====
 +
===== 현재노드의 태그가 닫힐때까지의 모든 노드 "Following" =====
 +
{{틀:고지 상자
 +
|내용= ''' Following '''
 +
# 주어진 부모 노드 뒤의 요소 찾기를 시작합니다.
 +
# 다음 문 앞의 요소를 찾아 최상위 노드로 설정 한 다음 해당 노드 이후의 모든 요소를 찾기 시작합니다.
 +
## 먼저 클래스 속성이있는이 XPath를 찾습니다.
 +
#::<source lang=java>driver.findElement(By.xpath("//div[@class='fusion-sliding-bar-wrapper']"));</source>
 +
## 그런 다음 해당 노드 이후의 모든 섹션 요소를 찾기 시작합니다.
 +
#::<source lang=java>driver.findElement(By.xpath("//div[@class='fusion-sliding-bar-wrapper']//following::section"));</source>
 +
}}
 +
https://548225-1759080-raikfcquaxqncofqfm.stackpathdns.com/wp-content/uploads/2018/05/Pasted-into-XPath-in-Selenium-The-Most-Complete-Guide-2021-Update-10-1024x393.png
 +
----
  
//div[@id='navigation']/ul/li[3]/a/span
+
=====  현재 노드의 형제 노드 "Following-sibling" =====
 +
{{틀:고지 상자
 +
|내용= '''Following-sibling'''
 +
# 컨텍스트 노드의 다음 형제를 선택.
 +
<source lang=xml>driver.findElement(By.xpath("//*[@class=’col-md-6 text-left’]/child::div[2]//*[@class=’panel-body’]//following-sibling::li"));</source>
 +
}}
  
In this blog, my prime focus will be to demonstrate the Relative XPath.
+
===== Child =====
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.
+
|내용= '''Child '''
 +
# 현재 노드의 모든 자식 요소를 선택합니다.
 +
<source lang=html>driver.findElement(By.xpath("//nav[@class=’fusion-main-menu’]//ul[@id=’menu-main’]/child::li"));</source>
  
.//div[@id='products']/a/img
+
}}
 +
https://548225-1759080-raikfcquaxqncofqfm.stackpathdns.com/wp-content/uploads/2018/05/Pasted-into-XPath-in-Selenium-The-Most-Complete-Guide-2021-Update-11-1024x335.png
  
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:
+
또한 아래와 같이 section [1], section [2], section [3] 등의 구문을 사용하여 필요한 "section"요소를 선택할 수 있습니다.
  
.//div[@id='products']//img
+
https://548225-1759080-raikfcquaxqncofqfm.stackpathdns.com/wp-content/uploads/2018/05/Pasted-into-XPath-in-Selenium-The-Most-Complete-Guide-2021-Update-12.png
  
Here I am trying to find an image tag which is the descendant of tag div.
+
===== Preceding =====
 +
{{틀:고지 상자
 +
|내용= '''Preceding'''
 +
# 현재 노드 앞에 오는 모든 노드를 선택합니다.
 +
# 먼저 맨 아래 요소를 찾은 다음 앞에 "li"를 사용하여 아래와 같이 모든 "li"요소를 찾습니다.
 +
<source lang=html>
 +
//div[@id='wrapper']/div[@class='fusion-sliding-bar-wrapper']//preceding::li
 +
</source>
 +
}}
  
Expression: .” & “..”
+
https://548225-1759080-raikfcquaxqncofqfm.stackpathdns.com/wp-content/uploads/2018/05/Pasted-into-XPath-in-Selenium-The-Most-Complete-Guide-2021-Update-13.png
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']/..
+
===== Ancestor =====
 +
{{틀:고지 상자
 +
|내용= ''' Ancestor '''
 +
# ancestor 요소를 찾아 최상위 노드로 설정 한 다음 해당 노드에서 요소를 찾기 시작합니다.  
 +
## 먼저 XPath가 //section [@ id =’content’] 인 요소를 찾습니다.
 +
## 그 다음 위의 XPath가 속한 노드에서 모든 div 요소를 찾기 시작합니다.
 +
<source lang=html>
 +
//section[@id=’content’]//ancestor::div
 +
</source>
  
This expression will find the parent node of the current node.
+
}}
  
Expression: “@”
+
https://548225-1759080-raikfcquaxqncofqfm.stackpathdns.com/wp-content/uploads/2018/05/Pasted-into-XPath-in-Selenium-The-Most-Complete-Guide-2021-Update-9.png
“@” is used to select attribute in the document tree.
 
In the above example I specify attribute id with “@” and the value products inside ‘ ’.
 
  
Expression: “*”
+
# //section[@id=’content’]//ancestor::div[1] – Returns 53 nodes
XPath support wildcard like “*”. Sometimes it is of much use to find a Relative path. Let’s see an example:
+
# //section[@id=’content’]//ancestor::div[2]- Returns 33 nodes
 +
# //section[@id=’content’]//ancestor::div[3] – Returns 24 nodes
 +
# //section[@id=’content’]//ancestor::div[4]- Returns 19 nodes
  
.//*[text()='Home']
+
===== Descendant =====
 +
{{틀:고지 상자
 +
|내용= ''' Descendant '''
 +
# 현재 요소의 노드 아래로 이동하는 현재 요소의 모든 하위 요소를 식별하고 반환합니다. 아래에서 XPath는 "menu-main"아래의 모든 "li"요소를 반환합니다.
 +
# 예시)
 +
<source lang=xml>
 +
//nav[@class=’fusion-main-menu’]//*[@id=’menu-main’]//descendant::li
 +
</source>
 +
}}
  
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.
+
https://548225-1759080-raikfcquaxqncofqfm.stackpathdns.com/wp-content/uploads/2017/09/descendant.png
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.
+
===== Parent =====
 +
{{틀:고지 상자
 +
|내용= '''Parent '''
 +
아래 예제와 같이 현재 노드의 부모를 반환합니다.
 +
<source lang=html>
 +
.//*[@id=’get-input’]/button//parent::form
 +
</source>
 +
}}
  
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')]
+
https://548225-1759080-raikfcquaxqncofqfm.stackpathdns.com/wp-content/uploads/2017/09/parent-selector-tactic-in-selenium.png
  
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()’:
 
  
 +
==== XPath 유용한 팁 ====
 +
# 대부분의 경우 로케이터의 속성이 동적으로 생성 될 때 문제가 발생합니다.
 +
#:그리고 지금은 거의 모든 웹 애플리케이션이이 전략을 따르고 있습니다.
 +
===== “contains” 키워드 =====
 +
# "contains ()"는 속성이름과 속성 값 , 두 개의 인수를받는 함수입니다.
 +
<source lang=html>
 +
.//div[contains(@id, 'search')]
 +
</source>
 +
* 'search'  값이 포함 된 'id'라는 속성이 포함 된 div 태그를 찾습니다.
 +
* 정확히 'search'일 필요는 없지만 패턴이 일치해야합니다.
 +
* 함수‘contains ()’는 패턴을 일치시켜 속성 이름을 값과 일치시킵니다.
 +
# 다음은‘contains ()’함수의 또 다른 사용법
 +
<source lang=html>
 
.//span[contains(text(), 'Hot')]
 
.//span[contains(text(), 'Hot')]
 
+
</source>
This expression finds a span tag which contains ‘Hot’ as text in it.
+
* 이 표현식은 텍스트로 'Hot'이 포함 된 span 태그를 찾습니다.
Expression using keyword “text():
+
* 키워드 "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:
+
* 앞에서 본 예에서는‘text ()’함수를 사용했습니다.  
 
+
# 'text ()’함수의 특정 텍스트가있는 특정 태그를 찾습니다.  
 +
<source lang=html>
 
.//span[text()= 'Home']
 
.//span[text()= 'Home']
 +
</source>
  
As I said this expression will find a span tag with text ‘Home’.
+
https://548225-1759080-raikfcquaxqncofqfm.stackpathdns.com/wp-content/uploads/2018/05/Pasted-into-XPath-in-Selenium-The-Most-Complete-Guide-2021-Update-7-1024x491.png
 
 
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:
 
  
 +
=====“starts-with()”키워드 =====
 +
# starts-with ()’ 속성 이름과 속성값 이라는 두 개의 인수를 사용합니다
 +
<source lang=java>
 
.//div[starts-with(@class, 'width')]
 
.//div[starts-with(@class, 'width')]
 
+
</source>
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.
+
* 여기서는 'width'로 시작하는 'class'속성이있는 div 태그를 찾음.
Another example:
+
# 다른 예시:
 
+
<source lang=java>
 
.//span[starts-with(text(), 'Gift')]
 
.//span[starts-with(text(), 'Gift')]
 +
</source>
 +
# 'contains ()’함수처럼  'text ()'함수를 사용하여 태그 안의 텍스트를 찾았습니다. 'starts-with ()'함수를 사용하여 수행 할 수도 있습니다.
  
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()’ .
+
https://548225-1759080-raikfcquaxqncofqfm.stackpathdns.com/wp-content/uploads/2018/05/Pasted-into-XPath-in-Selenium-The-Most-Complete-Guide-2021-Update-8-1024x465.png
 
 
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…
 

2021년 6월 9일 (수) 10:25 기준 최신판

thumb_up 추천메뉴 바로가기


1 Xpath 개요[편집]

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

android Selenium WebDriver 에서 요소(Element)를 찾는 로케이터(Locator)

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


1.1 XPath 란?[편집]

android 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 플러그인 사용 추천


1.2 XPath 표현식[편집]

1.2.1 절대경로 (Absolute Path)[편집]

android 절대경로

  1. 절대 경로는 계층 문서 내에서 노드를 선택하기 위해 모든 단일 노드를 지정하는 것을 의미합니다.
  2. 항상 루트 노드에서 시작합니다.


  1. 예시
/html/body/div[2]/div/div[4]/div/ul/li[3]/a/span

1.2.2 상대경로 (Relative Path)[편집]

android 상대경로

  1. 상대경로 XPath 표현식은 매우 길 수 있습니다.
  2. 중첩 된 각 관계에 대해 100% 존재해야 함. 그렇지 않으면 로케이터가 작동하지 않습니다.
    이러한 이유로 Relative XPath 표현식을 사용하는 것이 좋습니다.
  3. 상대 XPath 표현식에서는 선택한 노드에서 시작할 수 있습니다.
  4. 위의 절대 경로를 다음 상대 경로에도 쓸 수 있습니다.


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

1.2.3 슬래쉬 “/” 와 "//" 의미[편집]

android “/” 와 "//"

  1. XPath의 어느 곳에서나 하나의 슬래시 '/'는 상위 요소 내에서 바로 요소를 찾는 것을 의미합니다.
  2. 이중 슬래시‘//’는 상위 요소 내에서 하위 또는 손자 (하위) 요소를 찾는 것을 나타냅니다.


  1. 두가지 예시 참조
  2. 예시 1)
.//div[@id='products']/a/img
    1. 'a' 태그의 하위 인 html 문서에서 이미지 태그를 찾으려고합니다.
    2. 그리고 a 태그는 div 태그의 자식입니다.
    3. 동일한 img 태그는 다음에서 찾을 수 있습니다.
  1. 예시 2)
.//div[@id='products']//img

1.2.4 점 “.” 와 “..” 의미[편집]

android “.” 와 “..”

  1. "." 은 XPath에서 현재 노드를 지정하는 데 사용됩니다.
  2. ".." 은 문서 트리에서 한 단계 위로 이동하는 데 사용됩니다.
    즉, 현재 노드의 부모를 찾습니다.


  1. 예시)
.//div[@id='products']/..
  • 위 표현식은 현재 노드의 부모 노드를 찾습니다.

1.2.5 "@”의 의미[편집]

android “@”

  1. "@"는 문서 트리에서 속성을 선택하는 데 사용됩니다.
  2. 위의 예시에서 "@"로 속성 ID를 지정하고‘’안에 값 'products' 지정 함.


1.2.6 " * " 의 의미[편집]

android “ * ”

  1. XPath는 "*"와 같은 와일드 카드를 지원합니다.
    때로는 상대 경로를 찾는 데 많이 유용합니다.


  1. 예시 )
.//*[text()='Home']
.//a[@*='Home']
  • 이 경우 값이 'home'인 속성을 가진 요소를 찾으려고합니다.
  • 이 경우 속성 이름은 신경 쓰지 않습니다.

1.2.7 형제/자식/조상 요소 찾기[편집]

1.2.7.1 현재노드의 태그가 닫힐때까지의 모든 노드 "Following"[편집]

android Following

  1. 주어진 부모 노드 뒤의 요소 찾기를 시작합니다.
  2. 다음 문 앞의 요소를 찾아 최상위 노드로 설정 한 다음 해당 노드 이후의 모든 요소를 찾기 시작합니다.
    1. 먼저 클래스 속성이있는이 XPath를 찾습니다.
    driver.findElement(By.xpath("//div[@class='fusion-sliding-bar-wrapper']"));
    1. 그런 다음 해당 노드 이후의 모든 섹션 요소를 찾기 시작합니다.
    driver.findElement(By.xpath("//div[@class='fusion-sliding-bar-wrapper']//following::section"));


Pasted-into-XPath-in-Selenium-The-Most-Complete-Guide-2021-Update-10-1024x393.png


1.2.7.2 현재 노드의 형제 노드 "Following-sibling"[편집]

android Following-sibling

  1. 컨텍스트 노드의 다음 형제를 선택.
driver.findElement(By.xpath("//*[@class=’col-md-6 text-left’]/child::div[2]//*[@class=’panel-body’]//following-sibling::li"));


1.2.7.3 Child[편집]

android Child

  1. 현재 노드의 모든 자식 요소를 선택합니다.
driver.findElement(By.xpath("//nav[@class=’fusion-main-menu’]//ul[@id=’menu-main’]/child::li"));


Pasted-into-XPath-in-Selenium-The-Most-Complete-Guide-2021-Update-11-1024x335.png

또한 아래와 같이 section [1], section [2], section [3] 등의 구문을 사용하여 필요한 "section"요소를 선택할 수 있습니다.

Pasted-into-XPath-in-Selenium-The-Most-Complete-Guide-2021-Update-12.png

1.2.7.4 Preceding[편집]

android Preceding

  1. 현재 노드 앞에 오는 모든 노드를 선택합니다.
  2. 먼저 맨 아래 요소를 찾은 다음 앞에 "li"를 사용하여 아래와 같이 모든 "li"요소를 찾습니다.
//div[@id='wrapper']/div[@class='fusion-sliding-bar-wrapper']//preceding::li


Pasted-into-XPath-in-Selenium-The-Most-Complete-Guide-2021-Update-13.png

1.2.7.5 Ancestor[편집]

android Ancestor

  1. ancestor 요소를 찾아 최상위 노드로 설정 한 다음 해당 노드에서 요소를 찾기 시작합니다.
    1. 먼저 XPath가 //section [@ id =’content’] 인 요소를 찾습니다.
    2. 그 다음 위의 XPath가 속한 노드에서 모든 div 요소를 찾기 시작합니다.
//section[@id=’content’]//ancestor::div


Pasted-into-XPath-in-Selenium-The-Most-Complete-Guide-2021-Update-9.png

  1. //section[@id=’content’]//ancestor::div[1] – Returns 53 nodes
  2. //section[@id=’content’]//ancestor::div[2]- Returns 33 nodes
  3. //section[@id=’content’]//ancestor::div[3] – Returns 24 nodes
  4. //section[@id=’content’]//ancestor::div[4]- Returns 19 nodes
1.2.7.6 Descendant[편집]

android Descendant

  1. 현재 요소의 노드 아래로 이동하는 현재 요소의 모든 하위 요소를 식별하고 반환합니다. 아래에서 XPath는 "menu-main"아래의 모든 "li"요소를 반환합니다.
  2. 예시)
//nav[@class=’fusion-main-menu’]//*[@id=’menu-main’]//descendant::li



descendant.png

1.2.7.7 Parent[편집]

android Parent 아래 예제와 같이 현재 노드의 부모를 반환합니다.

.//*[@id=’get-input’]/button//parent::form



parent-selector-tactic-in-selenium.png


1.2.8 XPath 유용한 팁[편집]

  1. 대부분의 경우 로케이터의 속성이 동적으로 생성 될 때 문제가 발생합니다.
    그리고 지금은 거의 모든 웹 애플리케이션이이 전략을 따르고 있습니다.
1.2.8.1 “contains” 키워드[편집]
  1. "contains ()"는 속성이름과 속성 값 , 두 개의 인수를받는 함수입니다.
.//div[contains(@id, 'search')]
  • 'search' 값이 포함 된 'id'라는 속성이 포함 된 div 태그를 찾습니다.
  • 정확히 'search'일 필요는 없지만 패턴이 일치해야합니다.
  • 함수‘contains ()’는 패턴을 일치시켜 속성 이름을 값과 일치시킵니다.
  1. 다음은‘contains ()’함수의 또 다른 사용법
.//span[contains(text(), 'Hot')]
  • 이 표현식은 텍스트로 'Hot'이 포함 된 span 태그를 찾습니다.
  • 키워드 "text ()"를 사용한 표현식 :
  • 앞에서 본 예에서는‘text ()’함수를 사용했습니다.
  1. 'text ()’함수의 특정 텍스트가있는 특정 태그를 찾습니다.
.//span[text()= 'Home']

Pasted-into-XPath-in-Selenium-The-Most-Complete-Guide-2021-Update-7-1024x491.png

1.2.8.2 “starts-with()”키워드[편집]
  1. starts-with ()’ 속성 이름과 속성값 이라는 두 개의 인수를 사용합니다
.//div[starts-with(@class, 'width')]
  • 여기서는 'width'로 시작하는 'class'속성이있는 div 태그를 찾음.
  1. 다른 예시:
.//span[starts-with(text(), 'Gift')]
  1. 'contains ()’함수처럼 'text ()'함수를 사용하여 태그 안의 텍스트를 찾았습니다. 'starts-with ()'함수를 사용하여 수행 할 수도 있습니다.

Pasted-into-XPath-in-Selenium-The-Most-Complete-Guide-2021-Update-8-1024x465.png