XPath에는 다음이 포함됩니다. 텍스트, 다음 형제 및 조상 Selenium

🚀 스마트 요약

XPath에는 다음이 포함됩니다. 형제 및 조상 Selenium 구조화된 관계와 텍스트 패턴을 사용하여 정확한 웹 요소 식별을 지원합니다. 이러한 XPath 함수는 복잡한 DOM 계층 구조에서 자동화의 안정성, 유연성 및 유지 관리성을 향상시킵니다.

  • contains() 부분 텍스트가 있는 동적 요소를 찾아 텍스트 변화에 대한 견고성을 향상시킵니다.
  • 신청 following-sibling ancestor 요소 계층 구조를 효율적으로 탐색하기 위해tract 관련 노드.
  • 정교하고 정확한 요소 타겟팅을 위해 논리 연산자(AND, OR)와 함수를 결합합니다.
  • XPath 축(선행, 후손)을 활용하여 복잡한 DOM 트리를 체계적으로 탐색합니다.
  • 이러한 표현을 통합합니다. Selenium 유지 관리가 가능하고, 동적이고, 복원력이 뛰어난 웹 테스트 자동화를 위한 스크립트입니다.

XPath에는 다음이 포함됩니다.

XPath 포함이란 무엇입니까?

XPath에는 다음이 포함됩니다. `$`는 XPath 표현식 내의 함수로, 특정 텍스트를 포함하는 웹 요소를 검색하는 데 사용됩니다. 예를 들면 다음과 같습니다.tracXPath의 contains() 함수를 사용하여 웹페이지 전체에서 주어진 텍스트 값과 일치하는 모든 요소를 ​​찾습니다. XPath의 contains 함수는 부분 텍스트를 사용하여 요소를 찾을 수 있는 기능을 제공합니다.

예 - 텍스트가 포함되어 있습니다.

여기서 우리는 앵커를 검색하고 있습니다. '라는 텍스트가 포함되어 있습니다.SAP 중'.

"//h4/a[contains(text(),'SAP M')]"

XPath에는 다음이 포함됩니다.

참고: 다음 XPath 연습은 이것으로 연습할 수 있습니다. https://demo.guru99.com/test/selenium-xpath.html

간단한 경우 xpath 테스트 스크립트에 사용할 복잡한 웹 요소를 찾을 수 없는 경우, XPath 1.0 라이브러리의 함수를 사용해야 합니다. 이러한 함수를 조합하면 더욱 구체적인 XPath를 만들 수 있습니다.

👉 무료 라이브 등록 Selenium 테스트 프로젝트

XPath에서 형제를 따르기

A 형제자매 Selenium 웹드라이버 부모 요소의 형제인 웹 요소를 가져오는 데 사용되는 함수입니다. 부모 요소가 알려져 있으면 웹 요소를 쉽게 찾을 수 있으며, XPath 표현식의 형제 속성을 사용하여 위치를 지정할 수 있습니다. Selenium 웹드라이버.

XPath 예의 형제:
여기서 'a'의 형제 요소를 기준으로 'h4'를 찾습니다.

"//div[@class='canvas- graph']//a[@href='/accounting.html'][i[@class='icon-usd']]/following-sibling::h4"

XPath에서 형제를 따르기

선조: 부모 요소를 기준으로 요소를 찾으려면 XPath의 ancestor 속성을 사용하면 됩니다.

XPath에서 형제를 따르기

예를 들어 이 3가지 기능을 이해해 보겠습니다.

테스트 단계:

참고 : 이 튜토리얼이 제작된 날짜 이후로 홈페이지는 다음과 같습니다. Guru99 버전이 업데이트되었으므로 테스트를 실행하려면 데모 사이트를 사용하십시오.

  1. We Buy Orders 신청서를 클릭하세요. https://demo.guru99.com/test/guru99home/
  2. '가장 인기 있는 몇 가지 코스' 섹션에서 텍스트가 'SELENIUM'인 WebElement의 형제인 모든 Web Elements를 검색합니다.
  3. XPath 텍스트 포함, 상위, 형제 함수를 사용하여 요소를 찾습니다.

XPath에서 형제를 따르기

USING에는 텍스트와 XPath 형제가 포함되어 있습니다.

import java.time.Duration;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.testng.annotations.Test;

// If you prefer WebDriverManager (optional):
// import io.github.bonigarcia.wdm.WebDriverManager;

public class SiblingAndParentInXpath_Chrome {
    @Test
    public void testSiblingAndParentInXpath() {

        // === Option A: Use local ChromeDriver binary path ===
        // Update this path to your chromedriver location:
        System.setProperty("webdriver.chrome.driver", "C:\\chromedriver.exe");

        // === Option B: Use WebDriverManager (uncomment next line and remove Option A lines) ===
        // WebDriverManager.chromedriver().setup();

        ChromeOptions options = new ChromeOptions();
        // Add any flags you need, e.g. headless:
        // options.addArguments("--headless=new");

        WebDriver driver = new ChromeDriver(options);
        try {

            driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
            driver.manage().window().maximize();
            driver.get("https://demo.guru99.com/test/guru99home/");

            // Find all siblings (divs) next to the 'SELENIUM' tile within
            // the "A few of our most popular courses" section.
            // Steps encoded in XPath:
            // 1) Locate the H2 that contains the section title
            // 2) Move to its parent DIV
            // 3) Inside it, locate the link with text 'SELENIUM'
            // 4) From the SELENIUM tile's parent DIV, get following sibling tiles

            List<WebElement> dateBox = driver.findElements(By.xpath(
                "//h2[contains(., 'A few of our most popular courses')]/parent::div" +
                "//a[normalize-space(.)='SELENIUM']/parent::div" +
                "/following-sibling::div[contains(@class,'rt-grid-2')]"
            ));

            // Print the text of each sibling element
            for (WebElement el : dateBox) {
                System.out.println(el.getText());
            }

        } finally {
            driver.quit();
        }
    }
}

출력은 다음과 같습니다.

USING에는 텍스트와 XPath 형제가 포함되어 있습니다.

XPath 상위 항목 Selenium

XPath 상위 항목 Selenium 지정된 계층에서 특정 요소의 조상을 찾는 데 사용되는 함수입니다. 반환할 조상의 레벨 또는 멤버 레벨 대비 조상의 레벨을 명시적으로 지정할 수 있습니다. 조상으로부터 계층적 단계 수를 반환하여 사용자가 원하는 지정된 조상을 찾습니다.

이제 '인기 강좌' 섹션의 모든 요소를 ​​'SELENIUM'이라는 텍스트가 있는 앵커의 조상의 도움으로 검색해야 한다고 가정해 보겠습니다.

여기서 xpath 쿼리는 다음과 같습니다.

"//div[.//a[text()='SELENIUM']]/ancestor::div[@class='rt-grid-2 rt-omega']/following-sibling::div"

완료 Code

import java.time.Duration;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.testng.annotations.Test;

public class AncestorInXpath_Chrome {

@Test

    public void testAncestorInXpath() {

        // Set path to your ChromeDriver executable
        System.setProperty("webdriver.chrome.driver", "C:\\chromedriver.exe");

        ChromeOptions options = new ChromeOptions();
        WebDriver driver = new ChromeDriver(options);

        try {

            driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
            driver.manage().window().maximize();
            driver.get("https://demo.guru99.com/test/guru99home/");

            // Search all elements in 'Popular course' section 
            // using the ancestor of the 'SELENIUM' link

            List <WebElement> dateBox = driver.findElements(
                By.xpath("//div[.//a[text()='SELENIUM']]/ancestor::div[@class='rt-grid-2 rt-omega']/following-sibling::div")
            );

            // Print all sibling elements of the 'SELENIUM' tile

            for (WebElement element : dateBox) {
                System.out.println(element.getText());
            }

        } finally {
            driver.quit();
        }
    }
}

출력은 다음과 같습니다.

완료 Code

AND 및 OR 사용

AND와 OR를 사용하면 XPath 표현식에 두 가지 조건을 넣을 수 있습니다.

  • AND의 경우, 두 조건이 모두 참이어야만 해당 요소를 찾을 수 있습니다.
  • OR의 경우, 2가지 조건 중 하나라도 참이면 해당 요소를 찾습니다.

여기서 우리의 XPath 쿼리는 다음과 같습니다.

Xpath=//*[@type='submit' OR @name='btnReset']

Xpath=//input[@type='submit' and @name='btnLogin']

AND 및 OR 사용

테스트 단계:

  1. We Buy Orders 신청서를 클릭하세요. https://demo.guru99.com/v1/
  2. 이 섹션에서는 위의 데모 사이트를 사용하여 XPath의 다양한 기능을 가진 요소를 검색해 보겠습니다.

AND 및 OR, 상위, 시작 및 XPath 축을 사용하여 요소를 찾습니다.

AND OR 예

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

public class AND_OR {
	public static void main(String[] args) {
		WebDriver driver;
		WebElement w,x;
		System.setProperty("webdriver.chrome.driver","E://Selenium//Selenium_Jars//chromedriver.exe");
		 driver= new ChromeDriver();
 		 
         // Launch the application
     	 driver.get("https://www.guru99.com/");
     	 
     	//Search element using OR in the xpath
     	 w=driver.findElement(By.xpath("//*[@type='submit' OR @name='btnReset']"));
      	
     	 //Print the text of the element
			System.out.println(w.getText());
			
		//Search element using AND in the xpath
			x=driver.findElement(By.xpath("//input[@type='submit' and @name='btnLogin']"));	
			 
		//Print the text of the searched element
			System.out.println(x.getText());
			 
	//Close the browser
     driver.quit();
	}

}

XPath 상위 Selenium

상위 Selenium 웹 페이지에서 현재 선택된 노드의 부모 노드를 가져오는 데 사용되는 메서드입니다. 요소를 선택하고 XPath를 사용하여 부모 요소를 가져와야 하는 상황에서 매우 유용합니다. 또한 이 메서드는 부모 요소의 부모를 가져오는 데에도 사용됩니다.

여기서 우리의 XPath 쿼리는 다음과 같습니다.

Xpath=//*[@id='rt-feature']//parent::div

XPath 상위 Selenium

부모를 사용하는 XPath

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;


public class Parent {
	public static void main(String[] args) {
		WebDriver driver;
		WebElement w;
		
		System.setProperty("webdriver.chrome.driver","E://Selenium//Selenium_Jars//chromedriver.exe");
		 driver= new ChromeDriver();
 		 
         // Launch the application
     	 driver.get("https://www.guru99.com/");
     	 
     	 //Search the element by using PARENT
     	 w=driver.findElement(By.xpath("//*[@id='rt-feature']//parent::div"));
      	
		//Print the text of the searched element
     	 System.out.println(w.getText());
	 
	//Close the browser
     driver.quit();
	}
}

시작

Starts-with 함수를 사용하면 새로 고침이나 클릭, 제출 등의 다른 작업 시 속성이 동적으로 변경되는 요소를 찾을 수 있습니다.

여기서 XPath 쿼리는 다음과 같습니다.

Xpath=//label[starts-with(@id,'message')]

시작

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;


public class StartsWith {
	public static void main(String[] args) {
		WebDriver driver;
		WebElement w;
		
		System.setProperty("webdriver.chrome.driver","E://Selenium//Selenium_Jars//chromedriver.exe");
		 driver= new ChromeDriver();
 		 
         // Launch the application
     	 driver.get("https://www.guru99.com/");
     	 
     	 //Search the element by using starts-with
     	 w=driver.findElement(By.xpath("//label[starts-with(@id,'message')]"));
     	
     	 //Print the text of the searched element
     	System.out.println(w.getText());
     	 
     	//Close the browser
	        driver.quit();
	}
}

Xpath 축

XPath 축을 사용하면 웹 페이지에서 동적이고 매우 복잡한 요소를 찾을 수 있습니다. XPath 축에는 요소를 찾는 여러 가지 방법이 있습니다. 여기서는 몇 가지 방법을 설명합니다.

수행원: 이 함수는 특정 구성 요소의 직접 요소를 반환합니다.

여기서 XPath 쿼리는 다음과 같습니다.

Xpath=//*[@type='text']//following::input

다음을 사용하는 XPath
다음을 사용하는 XPath
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;


public class Following {
	public static void main(String[] args) {
		WebDriver driver;
		WebElement w;
		
		System.setProperty("webdriver.chrome.driver","E://Selenium//Selenium_Jars//chromedriver.exe");
		 driver= new ChromeDriver();
 		 
         // Launch the application
     	 driver.get("https://www.guru99.com/");
     	 
     	 //Search the element by using Following method
     	 w=driver.findElement(By.xpath("//*[@type='text']//following::input"));
      	
		//Print the text of the searched element
     	 System.out.println(w.getText());
	 
	//Close the browser
     driver.quit();
	}
}

선행: 이 함수는 특정 요소의 이전 요소를 반환합니다.

여기서 XPath 쿼리는 다음과 같습니다.

Xpath= //*[@type='submit']//preceding::input

선행을 사용하는 XPath

선행을 사용하는 XPath
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;


public class Preceding {
	public static void main(String[] args) {
		
		WebDriver driver;
		WebElement w;
		
		System.setProperty("webdriver.chrome.driver","E://Selenium//Selenium_Jars//chromedriver.exe");
		 driver= new ChromeDriver();
 		 
         // Launch the application
     	 driver.get("https://www.guru99.com/");
     	 
     	 //Search the element by using preceding method
     	 w=driver.findElement(By.xpath("//*[@type='submit']//preceding::input"));
      	
		//Print the searched element
     	 System.out.println(w.getText());
	 
	//Close the browser
     driver.quit();

	}
}

d) 하위 항목: 이 함수는 특정 요소의 하위 요소를 반환합니다.

여기서 XPath 쿼리는 다음과 같습니다.

Xpath= //*[@id='rt-feature']//descendant::a

하위 항목을 사용하는 XPath

하위 항목을 사용하는 XPath
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;


public class Descendant {
	public static void main(String[] args) {
		WebDriver driver;
		WebElement w;
		System.setProperty("webdriver.chrome.driver","E://Selenium//Selenium_Jars//chromedriver.exe");
		 driver= new ChromeDriver();
 		 
         // Launch the application
     	 driver.get("https://www.guru99.com/");
     	 
     	 //Search the element by using descendant method
     	 w=driver.findElement(By.xpath("//*[@id='rt-feature']//descendant::a"));
      	
		//Print the searched element
     	 System.out.println(w.getText());
	 
	//Close the browser
     driver.quit();
	}
}

자주 묻는 질문

XPath에서 /*는 XML 또는 HTML 문서의 모든 루트 수준 요소를 선택합니다. 즉, "루트 노드 바로 아래에 있는 모든 요소를 ​​선택한다"는 의미입니다. 예를 들어, HTML 문서에서 /*는 루트 바로 아래의 최상위 요소이기 때문입니다.

XPath의 contains() 함수는 속성이나 텍스트가 주어진 값과 부분적으로 일치하는 요소를 찾는 데 도움이 됩니다. 특히 정확한 문자열이 예측 불가능하거나 동적인 경우 유용합니다. 예를 들어, //div[contains(@class,'menu')] 어떤 것과도 일치합니다 그 클래스에는 "메뉴"라는 단어가 포함되어 있습니다.

클래스 속성 내에서 부분 일치를 기반으로 요소를 찾으려면 contains() 함수를 사용합니다. 예를 들어, //button[contains(@class,'submit')] "submit-btn"이나 "form-submit"처럼 "submit"을 포함하는 클래스 이름을 가진 모든 태그를 대상으로 합니다. 이는 동적 클래스 이름을 처리하는 유연한 방법입니다.

이 게시물을 요약하면 다음과 같습니다.