1. 絕對路徑定位
WebElement button = driver.findElement(By.xpath("/html/body/div/input[@value='提交']"));
2. 相對路徑定位
WebElement button = driver.findElement(By.xpath("//input[@value='提交']"));
3. 使用索引號定位
WebElement button = driver.findElement(By.xpath("//input[2]"));
4. 使用頁面屬性定位
WebElement img = driver.findElement(By.xpath("//img[@alt='auto-test']"));
5. 屬性模糊定位
WebElement img = driver.findElement(By.xpath("//img[starts-with(@alt,'blog')]"));
WebElement img = driver.findElement(By.xpath("//img[contains(@alt,'test')]"));
6. text()函數文本定位
WebElement text = driver.findElement(By.xpath("//*[text()='百度搜索']"));
WebElement text = driver.findElement(By.xpath("//a[contains(text(),'搜索')]"));
7.同級元素定位
後面加上“..”,表示回到父節點,回到父節點後再往下定位其他子節點如:
WebElement text = driver.findElement(By.xpath("//div[contains(@id,'title:')]/../button[1]");