参考网址:
http://www.seleniumhq.org/docs/03_webdriver.jsp#introducing-the-selenium-webdriver-api-by-example
1.跳转到页面:
driver.get("http://www.google.com");
2.定位元素:
By.id
<div id="coolestWidgetEvah">...</div>
WebElement element = driver.findElement(By.id("coolestWidgetEvah"));
3.By Class Name
这个一般会定位到许多的元素,因为一个页面上, 某种class的元素会有很多。
<div class="cheese">
<span>Cheddar</span>
</div>
<div class="cheese">
<span>Gouda</span>
</div>
List<WebElement> cheeses = driver.findElements(By.className("cheese"));
4.By Tag Name
<iframe src="..."></iframe>
WebElement frame = driver.findElement(By.tagName("iframe"));
5.By Name
<input name="cheese" type="text"/>
WebElement cheese= driver.findElement(By.name("cheese"));
6.By Link Text
完全匹配link text
<a href="http://www.google.com/search?q=cheese">cheese</a>>
WebElement cheese= driver.findElement(By.linkText("cheese"));
7.By Partial Link Text
匹配部分link text
<a href="http://www.google.com/search?q=cheese">search for cheese</a>>
WebElement cheese= driver.findElement(By.partialLinkText("cheese"));
8.By CSS
<div id="food">
<span class="dairy">milk</span>
<span class="dairy aged">cheese</span>
</div>
WebElement cheese = driver.findElement(By.cssSelector("#food span.dairy.aged"));
9.By xpath
<input type="text" name="example" />
<input type="text" name="other" />
List<WebElement> inputs = driver.findElements(By.xpath("//input"));
10.Using JavaScript
可以用javascript来定位元素,尽管返回的是一个DOM元素,但会自动转为一个WebElemnet的对象
WebElement element = (WebElement) ((JavascriptExecutor)driver).executeScript("return $('.cheese')[0]")
11.一些常用form表单的事情
/*Finding all the input elements to the every label on a page:*/
List<WebElement> labels = driver.findElements(By.tagName("label"));
List<WebElement> inputs = (List<WebElement>) ((JavascriptExecutor)driver).executeScript(
"var labels = arguments[0], inputs = []; for (var i=0; i < labels.length; i++){" +
"inputs.push(document.getElementById(labels[i].getAttribute('for'))); } return inputs;", labels);
/*User Input - Filling In Forms.下面这段代码,打印了每个option的值, 并且click了,选上了这个值*/
WebElement select = driver.findElement(By.tagName("select"));
List<WebElement> allOptions = select.findElements(By.tagName("option"));
for (WebElement option : allOptions) {
System.out.println(String.format("Value is: %s", option.getAttribute("value")));
option.click();
}
/*首先先uncheck所有的选项, 然后选上“Edam”这个选项。*/
Select select = new Select(driver.findElement(By.tagName("select")));
select.deselectAll();
select.selectByVisibleText("Edam");
/*然后提交表单*/
driver.findElement(By.id("submit")).click();