在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.tw/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.