XPathに含まれるもの: テキスト、次の兄弟と祖先 Selenium

XPath には何が含まれますか?

XPath には以下が含まれます は、特定のテキストを含む Web 要素を検索するために使用される Xpath 式内の関数です。 Web ページ全体で XPath contains() 関数を使用して、指定されたテキスト値に一致するすべての要素を抽出できます。 XPath の Contains には、部分的なテキストを含む要素を検索する機能があります。

例 - テキストが含まれています
ここでは、アンカーを検索しています。テキストには「SAP M'。

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

XPath に含まれるもの

注: 次のXPath演習をこの上で練習することができます https://demo.guru99.com/test/selenium-xpath.html

単純な場合 XPath テスト スクリプト用の複雑な Web 要素が見つからないため、XPath 1.0 ライブラリの関数を使用する必要があります。これらの関数を組み合わせることで、より具体的な XPath を作成できます。

XPath で兄弟をフォローする

A 兄弟姉妹 Selenium ウェブドライバー 親要素の兄弟である Web 要素を取得するために使用される関数です。親要素がわかっている場合は、Selenium WebDriver の Xpath 式の兄弟属性を使用して、Web 要素を簡単に見つけたり配置したりできます。

XPath 内の兄弟の例:
ここでは、「a」の兄弟要素に基づいて「h4」を見つけています。

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

XPath で兄弟をフォローする

祖先: 親要素に基づいて要素を見つけるには、XPath の ancestor 属性を使用できます。

XPath で兄弟をフォローする

例を使用してこれら 3 つの関数を理解しましょう –

テスト手順:

Note: チュートリアルの作成日以降、Guru99 のホームページが更新されているため、テストを実行するには代わりにデモ サイトを使用してください。

  1. に行く https://demo.guru99.com/test/guru99home/
  2. 「最も人気のあるコースのいくつか」セクションで、テキストが「SELENIUM」であるWeb要素の兄弟であるすべてのWeb要素を検索します。
  3. XPath テキストを使用して、祖先および兄弟関数を含む要素を見つけます。

XPath で兄弟をフォローする

USING にはテキストと XPath の兄弟が含まれます

import java.util.List;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.Test;

public class SiblingAndParentInXpath {

    @Test

    public void testSiblingAndParentInXpath(){

    	WebDriver driver;
    	String driverPath = "C:\\geckodriver.exe";
    	System.setProperty("webdriver.gecko.driver", driverPath);
        driver = new FirefoxDriver();        
        
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        driver.get("https://demo.guru99.com/test/guru99home/");

        //Search element inside 'Popular course' which are sibling of control 'SELENIUM' ,Here first we will find a h2 whose text is ''A few of our most popular courses' ,then we move to its parent element which is a 'div' , inside this div we will find a link whose text is 'SELENIUM' then at last we will find all of the sibling elements of this link('SELENIUM')
        
        List <WebElement> dateBox = driver.findElements(By.xpath("//h2[contains(text(),'A few of our most popular courses')]/parent::div//div[//a[text()='SELENIUM']]/following-sibling::div[@class='rt-grid-2 rt-omega']"));

        //Print all the which are sibling of the the element named as 'SELENIUM' in 'Popular course'
        for (WebElement webElement : dateBox) {
            System.out.println(webElement.getText());
        }     

        driver.close();
    }
}

出力は次のようになります:

USING にはテキストと XPath の兄弟が含まれます

XPath の祖先 Selenium

XPath の祖先 Selenium 指定されたレイヤーで特定のメンバーの祖先を見つけるために使用される関数です。返される祖先のレベル、またはメンバーのレベルに対する祖先のレベルを明示的に指定できます。祖先からの階層ステップの数を返し、ユーザーが必要とする指定された祖先を見つけます。

ここで、テキストが「SELENIUM」であるアンカーの祖先の助けを借りて、「人気コース」セクションのすべての要素を検索する必要があるとします。

ここでの xpath クエリは次のようになります

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

完全なコード

import java.util.List;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.Test;

public class AncestorInXpath{

@Test

    public void testAncestorInXpath(){

        WebDriver driver = new FirefoxDriver();             
		driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        driver.get("https://demo.guru99.com/test/guru99home/");

        //Search All elements in 'Popular course' section 
		//with the help of ancestor of the anchor whose text is 'SELENIUM'

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

        //Print all the which are sibling of the element named as 'SELENIUM' in 'Popular course'

        for (WebElement webElement : dateBox) {
            System.out.println(webElement.getText());
        }
     
        driver.quit();
    }
}

出力は次のようになります-

完全なコード

AND と OR の使用

AND と OR を使用すると、XPath 式に 2 つの条件を入れることができます。

  • AND の場合、2 つの条件が両方とも true である必要があり、その場合のみ要素が検索されます。
  • OR の場合、2 つの条件のいずれかが true である必要があり、その場合のみ要素が検索されます。

ここでの XPath クエリは次のようになります

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

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

AND と OR の使用

テスト手順:

  1. に行く 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 Web ページで選択されている現在のノードの親ノードを取得するために使用されるメソッドです。 これは、要素を選択し、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 軸を使用すると、Web ページ上の動的で非常に複雑な要素を見つけることができます。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 を使用して要素を検索できないことがあります。 このような状況では、xpath クエリとは異なる関数が必要になります。
  • XPath contains、parent、ancestors、following-sibling などの重要な XPath 関数がいくつかあります。
  • これらの関数を利用することで、複雑なXPath式を作成できます。XPathにおけるcontainsの使い方を具体的に理解する必要がある場合は、Seleniumのcontains関数を使用すると、部分的なテキスト一致に基づいてWeb要素を簡単に検索できます。

毎日のGuru99ニュースレター

今すぐ配信される最新かつ最も重要な AI ニュースで一日を始めましょう。