Selenium
Table of Contents
1. Selenium
Selenium 是自动测试 Web 应用程序的工具,它通过 WebDirver 来模拟用户在浏览器上的点击和输入等事件。
参考:
Selenium Documentation: http://www.seleniumhq.org/docs/
Selenium API documentation (Java): http://seleniumhq.github.io/selenium/docs/api/java/index.html
Selenium API documentation (Python): http://seleniumhq.github.io/selenium/docs/api/py/
1.1. Java 依赖包
在 maven 工程的 pom.xml 中增加下面依赖即可:
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>3.6.0</version>
</dependency>
2. Selenium 使用实例
2.1. 准备环境
2.1.1. 方式一
在测试前,要安装浏览器对应的 WebDriver 驱动。
参考:
https://developer.mozilla.org/en-US/docs/Mozilla/QA/Marionette/WebDriver
https://sites.google.com/a/chromium.org/chromedriver/
2.1.2. 方式二(推荐)
直接使用现成的 docker image(测试所用浏览器运行在 docker container 中,需要的 WebDriver 驱动已经安装好):
$ docker run -d -p "4444:4444" -p "5900:5900" selenium/standalone-chrome-debug
测试时,使用“http://localhost:4444/wd/hub” 作为 RemoteWebDriver 的 remoteAddress 参数即可。如果想要看到浏览器的具体操作步骤,可以用 VNC 客户端连接 localhost:5900(vnc 密码为“secret”)。
参考:
https://hub.docker.com/u/selenium/
https://github.com/SeleniumHQ/docker-selenium
https://github.com/SeleniumHQ/docker-selenium/wiki/Getting-Started-with-Hub-and-Nodes
2.2. 测试代码
下面使用 Selenium 自动在百度中搜索关键字“Cheese!”的例子:
import java.net.MalformedURLException;
import java.net.URL;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;
public class App {
public static void main(String[] args) throws MalformedURLException {
WebDriver driver = new RemoteWebDriver(new URL("http://localhost:4444/wd/hub"), DesiredCapabilities.chrome());
// And now use this to visit Baidu
driver.get("http://www.baidu.com");
// Alternatively the same thing can be done like this
// driver.navigate().to("http://www.baidu.com");
// Find the text input element by its id
WebElement element = driver.findElement(By.id("kw"));
// Enter something to search for
element.sendKeys("Cheese!");
// Now submit the form. WebDriver will find the form for us from the element
element.submit();
// Check the title of the page
System.out.println("Page title is: " + driver.getTitle());
// Baidu's search is rendered dynamically with JavaScript.
// Wait for the page to load, timeout after 10 seconds
(new WebDriverWait(driver, 10)).until(new ExpectedCondition<Boolean>() {
public Boolean apply(WebDriver d) {
return d.getTitle().toLowerCase().startsWith("cheese!");
}
});
System.out.println("Page title is: " + driver.getTitle());
// Close the browser
driver.quit();
}
}
用 VNC 客户端连接 localhost:5900 即可看到浏览器的具体操作步骤。
上面例子参考自:http://www.seleniumhq.org/docs/03_webdriver.jsp#introducing-the-selenium-webdriver-api-by-example