当前位置:首页 > Windows程序 > 正文

webdriver API中文文档

2021-03-27 Windows程序

标签:

1.1   下载selenium2.0的lib包

官方UserGuide:

1.2   用webdriver打开一个浏览器

我们常用的浏览器有firefox和IE两种,firefox是selenium支持得比较成熟的浏览器。但是做页面的测试,速度通常很慢,严重影 响持续集成的速度,这个时候建议使用HtmlUnit,不过HtmlUnitDirver运行时是看不到界面的,对调试就不方便了。使用哪种浏览器,可以 做成配置项,根据需要灵活配置。

打开firefox浏览器:

//Create a newinstance of the Firefox driver

WebDriver driver = newFirefoxDriver();

打开IE浏览器

//Create a newinstance of the Internet Explorer driver

WebDriver driver = newInternetExplorerDriver ();

打开HtmlUnit浏览器

//Createa new instance of the Internet Explorer driver    

WebDriverdriver = new HtmlUnitDriver();

  1.3   打开测试页面

对页面对测试,首先要打开被测试页面的地址(如:),web driver 提供的get方法可以打开一个页面:

// And now use thedriver to visit Google

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

1.4   GettingStarted

package org.openqa.selenium.example; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.support.ui.ExpectedCondition; import org.openqa.selenium.support.ui.WebDriverWait; public class Selenium2Example { public static voidmain(String[] args) { // Create a newinstance of the Firefox driver // Notice that theremainder of the code relies on the interface, // not the implementation. WebDriver driver = newFirefoxDriver(); // And now use this tovisit Google driver.get("http://www.google.com"); // Alternatively thesame thing can be done like this // driver.navigate().to(""); // Find the text inputelement by its name WebElement element =driver.findElement(By.name("q")); // Enter something tosearch for element.sendKeys("Cheese!"); // Now submit the form.WebDriver will find the form for us from the element element.submit(); // Check the title ofthe page System.out.println("Page title is: " + driver.getTitle()); // Google‘s search isrendered dynamically with JavaScript. // Wait for the pageto load, timeout after 10 seconds (newWebDriverWait(driver, 10)).until(new ExpectedCondition<Boolean>() { public Booleanapply(WebDriver d) { returnd.getTitle().toLowerCase().startsWith("cheese!"); } }); // Should see:"cheese! - Google Search" System.out.println("Page title is: " + driver.getTitle()); //Close the browser driver.quit(); } }

View Code

第2章        Webdirver对浏览器的支持 2.1   HtmlUnit Driver

优点:HtmlUnit Driver不会实际打开浏览器,运行速度很快。对于用FireFox等浏览器来做测试的自动化测试用例,运行速度通常很慢,HtmlUnit Driver无疑是可以很好地解决这个问题。

缺点:它对JavaScript的支持不够好,当页面上有复杂JavaScript时,经常会捕获不到页面元素。

使用:

WebDriver driver = new HtmlUnitDriver();

2.2   FireFox Driver

优点:FireFox Dirver对页面的自动化测试支持得比较好,很直观地模拟页面的操作,对JavaScript的支持也非常完善,基本上页面上做的所有操作FireFox Driver都可以模拟。

缺点:启动很慢,运行也比较慢,不过,启动之后Webdriver的操作速度虽然不快但还是可以接受的,建议不要频繁启停FireFox Driver。

使用:

WebDriver driver = new FirefoxDriver();

Firefox profile的属性值是可以改变的,比如我们平时使用得非常频繁的改变useragent的功能,可以这样修改:

温馨提示: 本文由Jm博客推荐,转载请保留链接: https://www.jmwww.net/file/68321.html