XPath съдържа: текст, следващ брат и предшественик в Selenium

🚀 Интелигентно обобщение

XPath съдържа, брат/сестра и прародител в Selenium позволяват прецизна идентификация на уеб елементи, използвайки структурирани взаимоотношения и текстови модели. Тези XPath функции подобряват надеждността, гъвкавостта и поддръжката на автоматизацията в сложни DOM йерархии.

  • употреба contains() да локализира динамични елементи с частичен текст, подобрявайки устойчивостта срещу текстови вариации.
  • Кандидатствай following-sibling намлява ancestor за ефективно преминаване през йерархиите на елементите и извличане на свързани възли.
  • Комбинирайте функции с логически оператори (И, ИЛИ) за прецизно и точно насочване към елементи.
  • Използвайте XPath осите (предходни, наследствени), за да навигирате систематично в сложни DOM дървета.
  • Интегрирайте тези изрази в Selenium скриптове за поддържаема, динамична и устойчива автоматизация на уеб тестове.

XPath съдържа

Какво съдържа XPath?

XPath съдържа е функция в XPath израз, която се използва за търсене на уеб елементи, съдържащи определен текст. Можем да извлечем всички елементи, които съответстват на дадената текстова стойност, използвайки функцията XPath contains() в цялата уеб страница. Contains в XPath има възможността да намери елемент с частичен текст.

Пример – съдържа текст

Тук търсим котва .съдържа текст като "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 Уебдрайвер е функция, използвана за извличане на уеб елемент, който е „sibling“ на родителския елемент. Ако родителският елемент е известен, тогава уеб елементът може лесно да бъде намерен или локализиран, което може да се направи чрез атрибута „sibling“ на XPath израза в Selenium WebDriver.

Пример за брат в XPath:
Тук, въз основа на родствения елемент на 'a', намираме 'h4'

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

Следване на брат или сестра в XPath

прародителЗа да намерим елемент въз основа на родителския елемент, можем да използваме атрибута ancestry на XPath.

Следване на брат или сестра в XPath

Нека разберем тези 3 функции, използвайки пример –

Стъпки на теста:

Забележка: От датата на създаване на урока, началната страница на Guru99 е актуализирана, така че използвайте демо сайта, за да провеждате тестове.

  1. Отиди https://demo.guru99.com/test/guru99home/
  2. В секцията „Няколко от най-популярните ни курсове“ търсете всички уеб елементи, които са братя и сестри на уеб елемент, чийто текст е „SELENIUM“.
  3. Ще намерим елементи, използвайки XPath функциите text contains, ancestor и sibling.

Следване на брат или сестра в XPath

ИЗПОЛЗВАНЕ Съдържа Text и XPath Sibling

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();
        }
    }
}

Изходът ще бъде като:

ИЗПОЛЗВАНЕ Съдържа Text и XPath Sibling

Предшественик на XPath в Selenium

Предшественик на XPath в Selenium е функция, използвана за намиране на предшественика на специфичен елемент на посочения слой. Нивото на предшественика, което ще бъде върнато, или нивото на предшественика спрямо нивото на члена може да бъде изрично зададено. Тя връща броя на йерархичните стъпки от предшественика, локализирайки посочения предшественик, който потребителят иска.

Да предположим, че трябва да търсим всички елементи в секцията „Популярни курсове“ с помощта на предшественика на котвата, чийто текст е „SELENIUM“.

Тук нашата xpath заявка ще бъде като

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

Пълен код

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();
        }
    }
}

Резултатът ще изглежда като-

Пълен код

Използване на И и ИЛИ

Чрез използване на AND и OR можете да поставите 2 условия в нашия XPath израз.

  • В случай на И, и двете условия трябва да са верни, само тогава се намира елементът.
  • В случай на ИЛИ, едно от двете условия трябва да е вярно, само тогава се намира елементът.

Тук нашата XPath заявка ще бъде така

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

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

Използване на И и ИЛИ

Стъпки на теста:

  1. Отиди https://demo.guru99.com/v1/
  2. В този раздел ще използваме горния демонстрационен сайт, за да търсим елементи с различни функции на 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 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 с помощта на Following
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 с помощта на Preceding

XPath с помощта на Preceding
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 документ, /* би съвпадало тъй като е елементът от най-високо ниво под корена.

Функцията contains() в XPath помага за намирането на елементи, чийто атрибут или текст частично съвпада с дадена стойност. Тя е особено полезна, когато точният низ е непредсказуем или динамичен. Например. //div[contains(@class,'menu')] съвпада с всяко чийто клас включва думата „меню“.

За да намерите елементи въз основа на частично съвпадение в атрибута им на клас, използвайте функцията contains(). Например. //button[contains(@class,'submit')] е насочен към всеки с име на клас, което включва „submit“, като например „submit-btn“ или „form-submit“. Това е гъвкав начин за работа с динамични имена на класове.

Обобщете тази публикация с: