Selenium有八种元素定位方式。 一、通过id 如图所示为百度搜索框,输入内容区域的id为:kw(key word)
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "/Users/aaa/selenium/Project/chromedriver");
WebDriver webDriver = new ChromeDriver();
webDriver.get("https://www.baidu.com/");
WebElement kw = webDriver.findElement(By.id("kw"));
kw.sendKeys("input : sendKeys");
}
测试结果如下: 二、通过name
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "chromedriver");
WebDriver webDriver = new ChromeDriver();
webDriver.get("https://www.baidu.com/");
WebElement kw = webDriver.findElement(By.name("wd"));
kw.sendKeys("input : sendKeys");
}
三、通过className
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "chromedriver");
WebDriver webDriver = new ChromeDriver();
webDriver.get("https://www.baidu.com/");
WebElement kw = webDriver.findElement(By.className("s_ipt"));
kw.sendKeys("input : sendKeys");
}
如果className有空格,需要用xpath
WebElement kw = webDriver.findElement(By.xpath("//*[@class=\"fm has-soutu has-voice\"]"));
四、通过linkText
WebElement kw = webDriver.findElement(By.linkText("换一换"));
五、通过partialLinkText
WebElement kw = webDriver.findElement(By.partialLinkText("换一换"));
六、通过css
WebElement kw = webDriver.findElement(By.cssSelector("#kw"));
七、通过xpath
WebElement kw = webDriver.findElement(By.xpath("//*[@id=\"kw\"]"));
八、通过tagName
WebElement kw = webDriver.findElement(By.tagName("body"));
|