XPath contiene: testo, fratello e antenato seguenti in Selenium
Che cosa contiene XPath?
XPath contiene è una funzione all'interno dell'espressione XPath che viene utilizzata per cercare gli elementi web che contengono un particolare testo. Possiamo estrarre tutti gli elementi che corrispondono al valore di testo fornito utilizzando la funzione XPath contiene() in tutta la pagina web. Contiene in XPath ha la capacità di trovare l'elemento con testo parziale.
Esempio: contiene testo
Qui stiamo cercando un'ancora che contenga testo come 'SAP M'.
"//h4/a[contains(text(),'SAP M')]"
NOTA: puoi esercitarti con il seguente esercizio XPath su questo https://demo.guru99.com/test/selenium-xpath.html
Se un semplice XPath non è in grado di trovare un elemento web complicato per il nostro script di test, dobbiamo utilizzare le funzioni della libreria XPath 1.0. Con la combinazione di queste funzioni possiamo creare XPath più specifici.
Seguire il fratello in XPath
A Fratello dentro Selenium Webdriver è una funzione utilizzata per recuperare un elemento web che è fratello dell'elemento genitore. Se l'elemento genitore è noto, è possibile trovare o individuare facilmente l'elemento web che può utilizzare l'attributo fratello dell'espressione Xpath nel webdriver selenium.
Fratello nell'esempio XPath:
Qui sulla base dell'elemento fratello di "a" troviamo "h4"
"//div[@class='canvas- graph']//a[@href='/accounting.html'][i[@class='icon-usd']]/following-sibling::h4"
Antenato: Per trovare un elemento sulla base dell'elemento genitore possiamo utilizzare l'attributo antenato di XPath.
Cerchiamo di comprendere queste 3 funzioni utilizzando un esempio:
Passaggi del test:
Nota: Dalla data di creazione del tutorial, la home page di Guru99 è stata aggiornata, quindi utilizza il sito demo per eseguire i test
- Vai su https://demo.guru99.com/test/guru99home/
- Nella sezione "Alcuni dei nostri corsi più popolari", cerca tutti gli Elementi Web che sono fratelli di un Elemento Web il cui testo è "SELENIUM"
- Troveremo l'elemento che utilizza il testo XPath contenente la funzione antenato e fratello.
UTILIZZO Contiene testo e fratello 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(); } }
L'output sarà come:
Antenato XPath in Selenium
Antenato XPath in Selenium è una funzione utilizzata per trovare l'antenato di un membro specifico al layer specificato. Il livello dell'antenato da restituire o il livello dell'antenato relativo al livello del membro può essere specificato esplicitamente. Restituisce il numero di passaggi gerarchici dall'antenato, individuando l'antenato specificato che l'utente desidera.
Supponiamo ora di dover cercare tutti gli elementi nella sezione "Corso popolare" con l'aiuto dell'antenato dell'ancora il cui testo è "SELENIUM"
Qui la nostra query xpath sarà come
"//div[.//a[text()='SELENIUM']]/ancestor::div[@class='rt-grid-2 rt-omega']/following-sibling::div"
Codice completo
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(); } }
L'output sarà simile a:
Utilizzando AND e OR
Usando AND e OR puoi inserire 2 condizioni nella nostra espressione XPath.
- In caso di AND entrambe le 2 condizioni dovrebbero essere vere, solo allora trova l'elemento.
- In caso di OR una qualsiasi delle 2 condizioni dovrebbe essere vera, solo allora troverà l'elemento.
Qui la nostra query XPath sarà come
Xpath=//*[@type='submit' OR @name='btnReset']
Xpath=//input[@type='submit' and @name='btnLogin']
Passaggi del test:
- Vai su https://demo.guru99.com/v1/
- Nella sezione verrà utilizzato il sito demo riportato sopra per cercare elementi con diverse funzioni di XPath.
Troverai un elemento che utilizza gli assi AND e OR, genitore, inizia con e XPath
AND OR Esempio
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 Genitore in Selenium
Genitore dentro Selenium è un metodo utilizzato per recuperare il nodo genitore del nodo corrente selezionato nella pagina web. È molto utile nella situazione in cui selezioni un elemento e devi ottenere l'elemento genitore utilizzando XPath. Questo metodo viene utilizzato anche per ottenere il genitore del genitore.
Qui la nostra query XPath sarà come
Xpath=//*[@id='rt-feature']//parent::div
XPath utilizzando Parent
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(); } }
Inizia con
Utilizzando la funzione Inizia con, puoi trovare l'elemento il cui attributo cambia dinamicamente durante l'aggiornamento o altre operazioni come clic, invio, ecc.
Qui la nostra query XPath sarà come
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(); } }
Assi Xpath
Utilizzando gli assi XPath, puoi trovare gli elementi dinamici e molto complessi su una pagina web. Gli assi XPath contengono diversi metodi per trovare un elemento. Qui, discuteremo alcuni metodi.
i seguenti: Questa funzione restituirà l'elemento immediato del particolare componente.
Qui la nostra query XPath sarà come
Xpath=//*[@type='text']//following::input
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(); } }
Precedente: Questa funzione restituirà l'elemento precedente del particolare elemento.
Qui la nostra query XPath sarà come
Xpath= //*[@type='submit']//preceding::input
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) Discendente: Questa funzione restituirà l'elemento discendente del particolare elemento.
Qui la nostra query XPath sarà come
Xpath= //*[@id='rt-feature']//descendant::a
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(); } }
Sommario
- Esistono alcune situazioni in cui XPath normale non può essere utilizzato per trovare un elemento. In tale situazione, abbiamo bisogno di funzioni diverse dalla query xpath.
- Esistono alcune funzioni XPath importanti, come XPath contiene, genitore, antenati, fratello/sorella successivi, ecc.
- Con l'aiuto di queste funzioni è possibile creare espressioni XPath complesse.