Selenium webdriver-UI Element定位

转:http://blog.csdn.net/jillliang/article/details/8206402

1.创建Fixfox web driver实例

  WebDriver driver =  new ForefoxDriver();

  WebDriver driver = new InternetExplorerDriver();

2.获取Web page

driver.get("http://www.google.com");

或者

driver.navigate().to("http://www.google.com");

//navigate().to和get()其实作用是一样的,但是navigate还可以进行浏览器的前进后退操作:

    driver.navigate().forward();

    driver.navigate.back();

3. 定位UI Element

    先安装FireBug(http://getfirebug.com/), 然后用FireBug定位页面元素的值。 如下图所示,只要把firebug的箭头放到要定位的元素上,就可以得到该元素对应标签的值, 比如goole的textbox:<input id="lst-ib" class="lst lst-tbb" type="text" maxlength="2048" name="q" autocomplete="off" size="41" title="Google 搜索" value="">, 然后我们就可以通过name, id, class等属性来定位这个输入框。

    

3.1. 通过id

WebElement element = driver.findElement(By.id("lst-ib"));

3.2. 通过class name

WebElement element = driver.findElement(By.className("lst lst-tbb"));

3.3. 通过Name

WebElement element = driver.findElement(By.name("q"));

3.4. 通过 Tag Name

WebElement frame =driver.findElement(By.tagName("iframe"));

3.5. 通过 Link Text

WebElement cheese=driver.findElement(By.linkText("cheese"));

3.6. 通过 Partial Link Text

WebElement cheese=driver.findElement(By.partialLinkText("cheese"));

3.7. 通过CSS

WebElementcheese=driver.findElement(By.cssSelector("#food span.dairy.aged"));

3.8. 通过XPATH [注意:XPATH在IE上速度会比较慢,所以推荐使用css selector]

List<WebElement>inputs=driver.findElements(By.xpath("//input"));


3.9. 通过JavaScript

WebElement element=(WebElement)((JavascriptExecutor)driver).executeScript("return $('.cheese')[0]");

原文地址:https://www.cnblogs.com/dieyaxianju/p/5015103.html