มารู้จักการเขียน Xpath กันเถอะ
- Supatchakorn
- Dec 16, 2018
- 1 min read
ในงาน automate test มีการเขียน locator ได้หลายรูปแบบ แต่ที่แนะนำมากๆก็คือ การเขียนแบบ xpath โดยการค้นหา locator แบบ xpath นั้นจะหาตามโครงสร้างของ XML document นอกจากนั้นยังสามารถเขียน Operators เข้าไปใน xpath ได้อีกด้วย
ตัวอย่างโครงสร้างของ XML document ที่ควรรู้ในการเขียน xpath

xpath แบ่งออกเป็น 2 แบบ
1. Absolute XPath คือการเขียนแบบค้นหาตาม tag name ตรงๆ
เช่น html/body/div/div[2]/div/div/div/div/div[2]/form/table/tbody/tr[2]/td[1]/input[1]

2. Relative XPath
เมื่อเราเขียนแบบ Ralative xpath มันสามารถเริ่มต้นค้นหา element ได้จากระบุ tag name , attribute name หรือ value ได้เลย โดยไม่ต้องเริ่มจาก tag แรกของ XML document เหมือนกับ Absolute XPath ซึ่งจะทำให้มีความแม่นยำมากกว่าและเข้าใจได้ง่ายกว่าอีกด้วย
Syntax for XPath : //tagname[@attribute='value']
// คือ เริ่มต้นค้นหาจาก tag name
@ คือ attribute name
/ คือ ค้นหา child tag จาก current tag
* คือ ค้นหาจากทุก tag หรือ attribute
.. คือ ค้นหา parents tag of current tag
1. Basic Xpath
ตัวอย่าง 1. //input[@name="email"]

// คือ เริ่มต้นค้นหา tag name ที่มีชื่อว่า input
@ คือ ค้นหา attribute name ชื่อ name และมี value = email
ตัวอย่าง 2. //*[@id="search-input"]/input[@id="search"]
* คือ ค้นหาทุก tag
/ คือ ค้นหา child tag ที่มีชื่อว่า input
or //*[@*="search-input"]/input[@id="search"]
* คือ ค้นหาทุก tag และ attribute ที่มี value = search-input

ตัวอย่าง 3. //input[@id="search"]/../../paper-tooltip
.. คือ ค้นหา parents tag ขึ้นไป 2 ชั้น
/ คือ ค้นหา child tag name = paper-tooltip

2. Xpath แบบ Contains() function : เราสามารถเขียนให้ xpath ค้นหาด้วย partial value
Syntax : //tagename[contains(@attribute,'partial value')]
ตัวอย่าง 1. //*[contains(@value,"ค้นแล้วเจอ")]

3. Xpath แบบ Start-with function : ตามชื่อเลยค่ะ ค้นหา xpath ที่มี value เริ่มต้นด้วยค่าที่เราใส่เข้าไป
Syntax : //tagename[starts-with(@attribute,'start-with value')]
ตัวอย่าง 1. //*[starts-with(@id,'search-')]
สามารถนำไปใช้ เมื่อเราต้องการ match หลาย element

4. Xpath by Text () : เป็นการค้นหา Element โดยค้นหาจาก Text
Syntax : //tagename[text()='Text Value']
ตัวอย่าง 1. //*[text()="อีเมลหรือโทรศัพท์"]

5. Select Last Xpath : Last() function จะค้นหา Element สุดท้ายที่ Match ได้จาก Xpath ที่เราระบุ
Syntax : //tagename[starts-with(@attribute,'value')][last()]
ตัวอย่าง 1. //div[starts-with(@id,'search-')][last()]
มันจะ Match กับ Xpath ตัวสุดท้ายที่ซ้ำกัน

ตัวอย่าง 2. //div[starts-with(@id,'search-')][last()-1]
มันจะ Match กับ Xpath ก่อน ตัวสุดท้ายที่ซ้ำกัน

6. Use And , Or in Xpath
Syntax : //tagename[@attribute1='value1' or @attribute2='value2']
ตัวอย่าง 1. //*[@id="search" or type="text1"]

Syntax : //tagename[@attribute1='value1' and @attribute2='value2']
ตัวอย่าง 2. //*[@name="search_query" and @placeholder="ค้นหา"]

ตัวอย่าง 3. การใช้ and , or ร่วมกัน
xpath=//*[@resource-id="segment_button" and (@text="ทดสอบ" or @text="Test")]
Comments