---> 1. By.id 以百度主页为例
<span classs = "bg s_ipt_wr">
<input type = "text"
name = "wd"
id = "kw"
maxlength = "100"
class = "s_ipt"
autocomplete = "off">
</span>
<span classs = "bg s_btn_wr">
<input type = "submit"
name = "百度一下"
id = "su"
class = "bg s_btn"
onmousedown = "this.className = 'bg s_btn_s_btn_h'
onmouseout = 'this.className = ‘bg s_btn’'>
</span>
在webDriver 中通过ID 查找元素的java 示例代码:
pubic class testBaiduById{
public static void main(String[] args){
WebDriver driver = new FirefoxDriver();
driver.get("http://baidu.com");
WebElement searchBox = driver.findElement(By.id("kw"));
searchBox.sendkeys("test Baidu By Id");
WebElement searchButton = driver.findElement(By.id("su"));
searchButton.submit();
driver.close();
}
}
---> 2. By.name
---> 3. By.tagName
---> 4. By.className
---> 5. By.linkText
<a href = "http://www.csdn.net/company/contact.html" target = "_blank">联系方式</a>
pubic class testBaiduByLinkText{
public static void main(String[] args){
WebDriver driver = new FirefoxDriver();
driver.get("http://csdn.com");
WebElement contactLink = driver.findElement(By.linkText("联系方式"));
contactLink.click;
driver.close();
}
}
---> 6. By.partialLinkText
<a href = "http://www.csdn.net/company/contact.html" target = "_blank">联系方式</a>
pubic class testBaiduByPartialLinkText{
public static void main(String[] args){
WebDriver driver = new FirefoxDriver();
driver.get("http://csdn.com");
WebElement contactLink = driver.findElement(By.partiallinkText("联系"));
contactLink.click;
driver.close();
}
}
---> 7. By.cssSelector
---> 8. By.Xpath
package com.morningstar.aa.pages;
import org.testng.annotations.Test;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.openqa.selenium.chrome.*;
import org.openqa.selenium.*;
import org.openqa.selenium.support.ui.Wait;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.WebDriverWait;
import static org.openqa.selenium.support.ui.ExpectedConditions.visibilityOfElementLocated;
public class testXPath {
WebDriver driver;
@BeforeClass
public void setUp(){
System.setProperty("webdriver.chrome.driver", "/Selenium 2/selenium/chromedriver");
driver = new ChromeDriver();
}
@AfterClass
public void tearDown(){
driver.close();
driver.quit();
}
@Test
public void testGoogle() throws InterruptedException{
driver.get("http://www.google.com");
WebElement searchBox = driver.findElement(By.xpath("//*[@id = "lst-ib"]"));
searchBox.sendKeys("selenium");
WebElement searchButton = driver.findElement(
By.xpath("//*[@id="tsf"]/div[2]/div[3]/center/input[]"));
searchButton.click();
Wait<WebDriver> wait = new WebDriverWait(driver, 30);
wait.until(visibilityOfElementLocated(
By.xpath("//*[@id = "rso"]/li[1]/div/h3/a/em")));
}
}