แต่ละตัวระบุตำแหน่ง (locator) มีความสำคัยเฉพาะ หากหน้ามีค่าแอตทริบิวต์ที่ไม่ซ้ำกัน ควรใช้ตัวเหล่านั้นก่อน แต่ถ้าไม่มีองค์ประกอบที่ไม่ซ้ำ ให้ใช้ css selector เพราะมีประสิทธิภาพด้านความเร็วมากกว่า
Css มีข้อจำกัดคือไม่สามารถเดินทางจาก child ไป parent node ได้ (ไม่สามารถย้อนกลับ) แต่ xpath อนุญาตให้ทำได้ Xpath เป็นตัวระบุตำแหน่งที่พบบ่อยที่สุดใน Selenium และทำการเดินทางผ่าน DOM elements และ attributes เพื่อระบุอ็อบเจกต์
Xpath แสดงได้สองแบบคือ '/' และ '//' สแลชเดียวหมายถึง absolute path ที่นี่ xpath เดินทางโดยตรงจาก parent ไป child ใน DOM ดังนั้นใน absolute xpath เราต้องเดินทางจาก root node ไปยังเป้าหมาย
Syntax -
driver.findElement(By.xpath("/html/body/div/input")).ดับเบิลสแลช '//' หมายถึง relative path ที่นี่ xpath หาองค์ประกอบที่ตรงกันในทุกมุมของ DOM ไม่มีจุดเริ่มต้นเฉพาะ
Syntax -
driver.findElement(By.xpath("//input[@name='Tutorial']")).แนะนำให้ใช้ relative xpath มากกว่า absolute xpath ใน absolute xpath เราต้องระบุจาก root ถึงองค์ประกอบที่ต้องการ ดังนั้นถ้าแอตทริบิวต์และค่าเปลี่ยนแปลงระหว่างทาง 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://www.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(); } }