Selenium 支援哪些不同的定位器?
Selenium 支援的各種定位器型別如下:
ID − 此屬性對每個元素都是唯一的。
語法 − driver.findElement(By.id("<<id 表示式>>")).
Name − 此屬性並非對每個元素都是唯一的。
語法 − driver.findElement(By.name("<<name 表示式>>")).
CSS 選擇器 − 可以從元素標籤和屬性中推匯出來。
語法 −
driver.findElement(By.cssSelector("<<tagname[attribute=’value’]>>")).
xpath − 可以從元素標籤和屬性中推匯出來。
語法 −
driver.findElement(By.xpath("<<//tagname[@attribute=’value’]>>")).
TagName − 可以從 HTML 標籤中推匯出來以識別元素。
語法 − driver.findElement(By.tagName("<<tagname>>")).
LinkText − 可以從錨文字中推匯出來以識別元素。
語法 − driver.findElement(By.linkText("<<錨文字>>")).
PartialLinkText − 可以從部分錨文字中推匯出來以識別元素。
語法 − driver.findElement(By.partialLinkText("<<部分錨文字>>")).
Classname − 可以從類名屬性中推匯出來。
語法 − driver.findElement(By.className("<<類名錶達式>>")).
示例
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 Locator { 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/index.htm"; driver.get(url); driver.manage().window().maximize(); driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); // Identify with Id attribute driver.findElement(By.Id("gsc-i-id1")).click(); // Identify with name attribute driver.findElement(By.name("search")).click(); //Identify with css attribute driver.findElement(By.cssSelector("input[name=’search’]")) .click(); //Identify with xpath attribute driver.findElement(By.xpath("//input[@name=’search’]")) .click(); // Identify with class name attribute driver.findElement(By.className("gsc-input")).click(); //Identify with link text attribute driver.findElement(By.linkText("Home")).click(); //Identify with partial link text attribute driver.findElement(By.partialLinkText("Hom")).click(); //Identify with tagname attribute driver.findElement(By.tagName("input")).click(); driver.close(); } }
廣告