如何在Selenium中使用XPath查詢元素?
我們可以使用Selenium webdriver和xpath定位器來查詢元素。
要使用xpath識別元素,表示式應為`//tagname[@attribute='value']`。
要使用xpath識別元素,表示式應為`//tagname[@class='value']`。xpath有兩種型別:相對路徑和絕對路徑。絕對路徑以`/`符號開頭,從根節點開始到我們要識別的元素。
例如:
/html/body/div[1]/div/div[1]/a
相對xpath以`//`符號開頭,不從根節點開始。例如:
//img[@alt='tutorialspoint']
讓我們看看從根節點開始的高亮顯示元素的html程式碼。
元素“Home”的絕對xpath是`/html/body/div[1]/div/div[1]/a`。
元素“Home”的相對xpath是`//a[@title='TutorialsPoint - Home']`。
還有一些可用的函式可以幫助構建相對xpath表示式:
`text()` – 用於根據頁面上可見的文字識別元素。xpath表示式為`//*[text()='Home']`。
`starts-with()` – 用於識別其屬性值以特定文字開頭的元素。此函式通常用於屬性值在每次頁面載入時都會更改的情況。
讓我們看看元素“Q/A”的html:
xpath表示式應為`//a[starts-with(@title, 'Questions &')]`。
`contains()` - 它識別其屬性值包含實際屬性值子文字的元素。此函式通常用於屬性值在每次頁面載入時都會更改的情況。
xpath表示式為:`//a[contains(@title, 'Questions & Answers')]`。
語法
WebElement m = driver.findElement(By.xpath("//span[@class = 'cat-title']"));
示例
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; import java.util.concurrent.TimeUnit; public class LocatorXpath{ public static void main(String[] args) { System.setProperty("webdriver.gecko.driver", "C:\Users\ghs6kor\Desktop\Java\geckodriver.exe"); WebDriver driver = new FirefoxDriver(); //implicit wait driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); //URL launch driver.get("https://tutorialspoint.tw/online_dev_tools.htm"); // identify element with xpath WebElement n=driver. findElement(By.xpath("//span[@class = 'cat-title']")); String str = n.getText(); System.out.println("Text is : " + str); driver.close(); } }
輸出
廣告