Si es simple XPath Al no poder encontrar una característica web compleja para nuestro script de prueba, necesitamos usar las funciones de la biblioteca XPath 1.0. Con la combinación de estas funciones, podemos crear un XPath más específico. Analicemos 3 de tales funciones:
Estudiémoslos en detalle –
¿Qué hay () en el selenio?
contiene () en selenio es una función dentro de la expresión Xpath que se utiliza para buscar los elementos web que contienen cierto texto. Podemos eliminar todos los elementos que coincidan con el valor de texto dado utilizando la función XPath () en la página web. XPath tiene la capacidad de encontrar el elemento con texto parcial.
Ex. Aquí buscamos un ancla. Incluye texto como ‘SAP M’.
"//h4/a[contains(text(),'SAP M')]"
NOTA: Puede practicar el siguiente ejercicio XPath en este http://demo.guru99.com/test/selenium-xpath.html
¿Qué es Sibling en Selenium Webdriver?
UNA. Hermano en Selenium Webdriver es una función que se utiliza para encontrar un elemento web que sea hermano del elemento principal. Si se conoce el elemento principal, entonces el elemento web se puede encontrar o encontrar fácilmente, lo que puede usar el atributo hermano de la expresión Xpath en una web web de selenio.
Hermano en XPath Ejemplo: aquí, sobre la base de un elemento hermano de ‘a’, obtenemos ‘h4’
"//div[@class="canvas- graph"]//a[@href="https://www.guru99.com/accounting.html"][i[@class="icon-usd"]]/following-sibling::h4"
Antepasados: Para obtener un elemento sobre la base del elemento padre, podemos usar el atributo de ancestro XPath.
Entendamos estas 3 funciones usando un ejemplo:
Pasos de prueba
Nota: Desde la fecha de creación del tutorial, la página de inicio de Guru99 se ha actualizado, así que use el sitio de demostración en su lugar para ejecutar pruebas.
- Ir http://demo.guru99.com/test/guru99home/
- En la sección ‘Algunos de los cursos más populares’, busque todos los elementos web hermanos con WebElement cuyo texto sea ‘SELENIUM’
- Encontramos que un elemento que usa texto XPath tiene una función de ancestro y hermano.
USE Sibling y XPath son hermanos
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("http://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(); } }
La salida será como:
Ancestros en Selenium Webdriver
Ancestros en Selenium Webdriver es una función que se utiliza para encontrar el antepasado de un miembro en particular en la capa especificada. Se puede especificar explícitamente el nivel de antepasado que se devolverá o el nivel de antepasado en relación con el nivel del miembro. Devuelve el número de pasos jerárquicos del ancestro, encontrando el ancestro especificado que desea el usuario.
Ahora probablemente tengamos que buscar todos los elementos en la sección ‘Curso común’ con la ayuda del ancestro ancla cuyo texto es ‘SELENIO’
Así será nuestra consulta de xpath
"//div[.//a[text()='SELENIUM']]/ancestor::div[@class="rt-grid-2 rt-omega"]/following-sibling::div"
Código 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("http://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(); } }
La salida aparecerá-
Usando AND y OR
Al usar AND y OR, puede agregar 2 condiciones en nuestra expresión XPath.
- Para Y ambas condiciones deben ser verdaderas, entonces solo encuentra el elemento.
- Para OR, cualquiera de las 2 condiciones debería ser verdadera, entonces solo encuentra el elemento.
Aquí nuestra pregunta XPath se verá así
Xpath=//*[@type="submit" OR @name="btnReset"]
Xpath=//input[@type="submit" and @name="btnLogin"]
Pasos de prueba:
- Ir http://demo.guru99.com/v1/
- En esta sección, el sitio de demostración anterior se utilizará para buscar un elemento con varias funciones XPath.
Encontrará un elemento utilizando los ejes AND y OR, parent, boot y XPath
Y O Ejemplo
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(); } }
¿Qué es un padre en selenio?
Padre en selenio es un método utilizado para recuperar el nodo principal del nodo seleccionado actual en la página web. Es muy útil en el caso de que seleccione un elemento y cuando necesite encontrar el elemento padre usando Xpath. Este método también se utiliza para encontrar el padre del padre.
Aquí nuestra pregunta XPath se verá así
Xpath=//*[@id='rt-feature']//parent::div
XPath usando 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(); } }
Empezando con
Usando la función Comenzar con, puede cambiar dinámicamente el elemento cuyas características cambian al actualizar u otras operaciones como hacer clic, insertar, etc.
Aquí nuestra pregunta XPath se verá así
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(); } }
Hachas Xpath
Mediante el uso de ejes XPath, puede encontrar los elementos dinámicos y altamente complejos de una página web. Los ejes XPath tienen varios métodos para encontrar un elemento. Aquí discutiremos algunos métodos.
siguiente: Esta función devolverá inmediatamente la característica del componente en particular.
Así es como se verá nuestra consulta XPath
Xpath=//*[@type="text"]//following::input
XPath usando lo siguiente
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(); } }
Antes: Esta función devolverá el elemento anterior del elemento dado.
Aquí nuestra pregunta XPath se verá así
Xpath= //*[@type="submit"]//preceding::input
XPath usando 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) Extracto: Esta función devolverá el elemento derivado del elemento particular.
Aquí nuestra pregunta XPath se verá así
Xpath= //*[@id='rt-feature']//descendant::a
XPath usando Extraer
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(); } }
Resumen
- Hay algunos casos en los que no se puede utilizar un XPath normal para encontrar un elemento. En tal caso, necesitamos diferentes funciones de la consulta xpath.
- Hay algunas funciones importantes de XPath como XPath, padre, antepasado, hermano posterior, etc.
- Con la ayuda de estas funciones, puede crear expresiones XPath complejas.