在id、name、xpath和css中,应该使用哪个定位器?


每个定位器都有一定的意义。如果页面包含唯一的

属性值,我们应该首先使用它们。但是,如果没有唯一的元素,我们应该使用css选择器,因为它在速度方面更有效。

Css也有一个缺点,就是我们不能从子节点遍历到父节点,这意味着我们不能向后遍历。但xpath允许此功能。Xpath是Selenium中最常见的定位器,它通过DOM元素和属性进行遍历来识别对象。

xpath以两种方式表示,即‘/’和‘//’。一个正斜杠表示绝对路径。在这里,xpath直接从父节点到子节点遍历DOM。因此,在绝对xpath中,我们必须从根节点遍历到目标。

语法:

driver.findElement(By.xpath("/html/body/div/input")).

双正斜杠‘//’表示相对路径。在这里,xpath在DOM的每个角落查找匹配的元素。它没有特定的起点。

语法:

driver.findElement(By.xpath("//input[@name=’Tutorial’]")).

始终建议使用相对xpath而不是绝对xpath。在绝对xpath中,我们需要从根节点指定到所需元素,所以如果中间任何属性及其值发生更改,那么我们的xpath将不再正确。

示例

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
public class TextMatch {
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver",    "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      String url = " https://tutorialspoint.com/questions/index.php";
      driver.get(url);
      driver.manage().window().maximize();
      driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
      //identifying element with xpath
      driver.findElement(By.xpath("//input[@class=’gsc-input’]")).click();
      driver.close();
   }
}

更新于:2020年6月10日

330 次浏览

启动您的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.