Selenium 的 webdriver


  Selenium 的 webdriver 
2019-3-19


注意:我们目前正在编写这些部分的文档。我们相信这里的信息是准确的,但请注意我们仍然在编写本章。我们将提供更多信息,这将使本章更加扎实。

引进的webdriver
Selenium 2.0的主要新功能是集成WebDriver API。除了解决Selenium-RC API中的一些限制之外,WebDriver还旨在提供更简单,更简洁的编程接口。Selenium-WebDriver的开发是为了更好地支持动态网页,页面元素可能会在不重新加载页面的情况下发生变化。WebDriver的目标是提供精心设计的面向对象的API,为现代高级Web应用程序测试问题提供改进的支持。

与Selenium-RC相比,WebDriver如何“驱动”浏览器?
Selenium-WebDriver使用每个浏览器对自动化的支持直接调用浏览器。如何进行这些直接调用,以及它们支持的功能取决于您使用的浏览器。有关每个“浏览器驱动程序”的信息将在本章后面提供。

对于熟悉Selenium-RC的人来说,这与你习惯的完全不同。Selenium-RC以相同的方式为每个支持的浏览器工作。它在浏览器加载时将“javascript函数”注入浏览器,然后使用其javascript在浏览器中驱动AUT。WebDriver不使用此技术。同样,它使用浏览器内置的自动化支持直接驱动浏览器。


WebDriver和Selenium-Server
您可能需要也可能不需要Selenium Server,具体取决于您打算如何使用Selenium-WebDriver。如果您的浏览器和测试都在同一台机器上运行,并且您的测试只使用WebDriver API,那么您不需要运行Selenium-Server; WebDriver将直接运行浏览器。

有一些原因可以将Selenium-Server与Selenium-WebDriver一起使用。

您正在使用Selenium-Grid在多台计算机或虚拟机(VM)上分发测试。
您希望连接到具有特定浏览器版本但不在当前计算机上的远程计算机。
您没有使用Java绑定(即Python,C#或Ruby),并且希望使用HtmlUnit Driver
设置Selenium-WebDriver项目
安装Selenium意味着在开发中设置项目,以便您可以使用Selenium编写程序。如何执行此操作取决于您的编程语言和开发环境。

Java
设置Selenium 2.0 Java项目的最简单方法是使用Maven。Maven将下载java绑定(Selenium 2.0 java客户端库)及其所有依赖项,并将使用maven pom.xml(项目配置)文件为您创建项目。完成此操作后,您可以将maven项目导入首选IDE,IntelliJ IDEA或Eclipse。

首先,创建一个包含Selenium项目文件的文件夹。然后,要使用Maven,您需要一个pom.xml文件。这可以使用文本编辑器创建。我们不会详细介绍pom.xml文件或使用Maven,因为已经有很好的参考资料。你的pom.xml文件看起来像这样。在为项目创建的文件夹中创建此文件。

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
                 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
        <groupId>MySel20Proj</groupId>
        <artifactId>MySel20Proj</artifactId>
        <version>1.0</version>
        <dependencies>
            <dependency>
                <groupId>org.seleniumhq.selenium</groupId>
                <artifactId>selenium-server</artifactId>
                <version>3.0.1</version>
            </dependency>
        </dependencies>
</project>

请务必指定最新版本。在撰写本文时,上面列出的版本是最新版本,但是在Selenium 2.0发布后会立即发布。检查当前版本的Maven下载页面并相应地编辑上述依赖项。

现在,从命令行,CD进入项目目录并运行maven,如下所示。

mvn clean install
这将下载Selenium及其所有依赖项,并将它们添加到项目中。

最后,将项目导入首选开发环境。对于那些不熟悉这一点的人,我们提供了一个显示这一点的附录。

将maven项目导入IntelliJ IDEA。 将maven项目导入Eclipse。

C#
从Selenium 2.2.0开始,C#绑定作为一组已签名的dll与其他依赖dll一起分发。在2.2.0之前,所有Selenium dll都是未签名的。要在项目中包含Selenium,
只需从http://selenium-release.storage.googleapis.com/index.html下载最新的selenium-dotnet zip文件。如果您使用的是Windows Vista或更高版本,则应在解压缩之前取消阻止zip文件:右键单击zip文件,单击“属性”,单击“取消阻止”,然后单击“确定”。

解压缩zip文件的内容,并在Visual Studio(或您选择的IDE)中为每个解压缩的dll添加对项目的引用。

官方NuGet包: RC WebDriver WebDriverBackedSelenium 支持

Python的
如果您使用Python进行测试自动化,那么您可能已经熟悉使用Python进行开发。要将Selenium添加到Python环境,请从命令行运行以下命令。

pip install selenium
pip要求PIP进行安装,PIP也有依赖setuptools的。

教学Python开发本身超出了本文档的范围,但是Python上有许多资源,组织中的开发人员可能会帮助您加快速度。

Ruby
如果您使用Ruby进行测试自动化,那么您可能已经熟悉Ruby中的开发。要将Selenium添加到Ruby环境,请从命令行运行以下命令。

gem install selenium-webdriver
教学Ruby开发本身超出了本文档的范围,但是Ruby上有许多资源,组织中的开发人员可能会帮助您加快速度。

Perl的
Perl绑定由第三方提供,请参阅有关如何安装/入门的任何文档。在撰写本文时,有一个已知的Perl绑定。

PHP
PHP绑定由第三方提供,请参阅有关如何安装/入门的任何文档。目前有三种已知的绑定:由Chibimagic By Lukasz Kolczynski和Facebook

JavaScript的
如果您使用node.js开发应用程序,则selenium项目会在npm上提供Javascript绑定。

使用npm安装Javascript绑定:

npm install selenium-webdriver
您可以在此处找到API文档。

从Selenium 1.0迁移
对于已经使用Selenium 1.0编写测试套件的用户,我们提供了有关如何将现有代码迁移到Selenium 2.0的提示。Selenium 2.0的首席开发人员Simon Stewart撰写了一篇关于从Selenium 1.0迁移的文章。我们将此作为附录包含在内。

从Selenium RC迁移到Selenium WebDriver

通过实施例引入Selenium 的webdriver API
WebDriver是一种用于自动化Web应用程序测试的工具,特别是用于验证它们是否按预期工作。它旨在提供一个易于探索和理解的友好API,比Selenium-RC(1.0)API更易于使用,这将有助于使您的测试更易于阅读和维护。它不依赖于任何特定的测试框架,因此它可以在单元测试项目中使用,也可以从普通的“主”方法中使用。本节介绍WebDriver的API,帮助您开始熟悉它。首先,如果您还没有设置WebDriver项目。这在上一节“ 设置Selenium-WebDriver项目”中有所描述。

设置项目后,您可以看到WebDriver的行为与任何普通库一样:它完全是自包含的,您通常不需要记住在使用它之前启动任何其他进程或运行任何安装程序,而不是使用Selenium-RC到代理服务器。

注意:使用ChromeDriver,Opera Driver,Android Driver 和iOS Driver需要执行其他步骤

你现在准备写一些代码了。一个简单的入门方法就是这个例子,它在Google上搜索术语“Cheese”,然后将结果页面的标题输出到控制台 (下面是各种语言的写法)。
java
 
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 void main(String[] args) {
        // Create a new instance of the Firefox driver
        // Notice that the remainder of the code relies on the interface,
        // not the implementation.
        WebDriver driver = new FirefoxDriver();

        // And now use this to visit Google
        driver.get("http://www.google.com");
        // Alternatively the same thing can be done like this
        // driver.navigate().to("http://www.google.com");

        // Find the text input element by its name
        WebElement element = driver.findElement(By.name("q"));

        // 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());
        
        // Google'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!");
            }
        });

        // Should see: "cheese! - Google Search"
        System.out.println("Page title is: " + driver.getTitle());
        
        //Close the browser
        driver.quit();
    }
}

C#

using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;

// Requires reference to WebDriver.Support.dll
using OpenQA.Selenium.Support.UI;

class GoogleSuggest
{
    static void Main(string[] args)
    {
        // Create a new instance of the Firefox driver.
        // Note that it is wrapped in a using clause so that the browser is closed
        // and the webdriver is disposed (even in the face of exceptions).

        // Also note that the remainder of the code relies on the interface,
        // not the implementation.

        // Further note that other drivers (InternetExplorerDriver,
        // ChromeDriver, etc.) will require further configuration
        // before this example will work. See the wiki pages for the
        // individual drivers at http://code.google.com/p/selenium/wiki
        // for further information.
        using (IWebDriver driver = new FirefoxDriver())
        {
            //Notice navigation is slightly different than the Java version
            //This is because 'get' is a keyword in C#
            driver.Navigate().GoToUrl("http://www.google.com/");
    
            // Find the text input element by its name
            IWebElement query = driver.FindElement(By.Name("q"));
    
            // Enter something to search for
            query.SendKeys("Cheese");
    
            // Now submit the form. WebDriver will find the form for us from the element
            query.Submit();
    
            // Google's search is rendered dynamically with JavaScript.
            // Wait for the page to load, timeout after 10 seconds
            var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
            wait.Until(d => d.Title.StartsWith("cheese", StringComparison.OrdinalIgnoreCase));
    
            // Should see: "Cheese - Google Search" (for an English locale)
            Console.WriteLine("Page title is: " + driver.Title);
        }
    }
}

paython

from selenium import webdriver
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support.ui import WebDriverWait # available since 2.4.0
from selenium.webdriver.support import expected_conditions as EC # available since 2.26.0

# Create a new instance of the Firefox driver
driver = webdriver.Firefox()

# go to the google home page
driver.get("http://www.google.com")

# the page is ajaxy so the title is originally this:
print driver.title

# find the element that's name attribute is q (the google search box)
inputElement = driver.find_element_by_name("q")

# type in the search
inputElement.send_keys("cheese!")

# submit the form (although google automatically searches now without submitting)
inputElement.submit()

try:
    # we have to wait for the page to refresh, the last thing that seems to be updated is the title
    WebDriverWait(driver, 10).until(EC.title_contains("cheese!"))

    # You should see "cheese! - Google Search"
    print driver.title

finally:
    driver.quit()

Ruby
require 'rubygems'
require 'selenium-webdriver'

driver = Selenium::WebDriver.for :firefox
driver.get "http://google.com"

element = driver.find_element :name => "q"
element.send_keys "Cheese!"
element.submit

puts "Page title is #{driver.title}"

wait = Selenium::WebDriver::Wait.new(:timeout => 10)
wait.until { driver.title.downcase.start_with? "cheese!" }

puts "Page title is #{driver.title}"
driver.quit

javaScript

var driver = new webdriver.Builder().build();
driver.get('http://www.google.com');

var element = driver.findElement(webdriver.By.name('q'));
element.sendKeys('Cheese!');
element.submit();

driver.getTitle().then(function(title) {
  console.log('Page title is: ' + title);
});

driver.wait(function() {
  return driver.getTitle().then(function(title) {
    return title.toLowerCase().lastIndexOf('cheese!', 0) === 0;
  });
}, 3000);

driver.getTitle().then(function(title) {
  console.log('Page title is: ' + title);
});

driver.quit();

Perl

use Selenium::Remote::Driver;

# Create a new instance of the driver
my $driver = Selenium::Remote::Driver->new;

# Go to the google homepage
$driver->get("http://www.google.com");

# Print original page title
my $title = $driver->get_title();
print "$title\n";

# Find the element that's name attribute is q (google search box)
my $inputElement = $driver->find_element("q", "name");

# type in the search
$inputElement->send_keys("cheese!");

# submit the form (although google automatically searches now without submitting)
$inputElement->submit();

# Set the timeout for searching for elements to 10 seconds (0 by default)
$driver->set_implicit_wait_timeout(10000);
# then use XPath to search for a page title containing cheese!
$driver->find_element("/html/head/title[contains(translate(., 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'), 'cheese!')]");

# You should see "cheese! - Google Search"
$title = $driver->get_title();
print "$title\n";

$driver->quit();


Selenium-WebDriver API Commands and Operations
在接下来的部分中,您将了解有关如何使用WebDriver的更多信息,例如在浏览器的历史记录中向前和向后导航,以及如何测试使用框架和窗口的网站。我们还提供了更全面的讨论和示例。

Selenium-WebDriver API命令和操作
获取页面
您可能想要使用WebDriver做的第一件事是导航到页面。执行此操作的常规方法是调用“get”:

java
driver.get("http://www.google.com");
csharp
driver.Url = "http://www.google.com";
ruby
driver.get "http://www.google.com"
python
driver.get("http://www.google.com")
perl
$driver->get('http://www.google.com')
javascript
driver.get('http://www.google.com');

根据几个因素,包括操作系统/浏览器组合,WebDriver可能会也可能不会等待页面加载。在某些情况下,WebDriver可能会在页面完成甚至开始加载之前返回控件。为确保稳健性,
您需要使用显式和隐式等待等待页面中存在的元素 。you need to wait for the element(s) to exist in the page using Explicit and Implicit Waits.

定位UI元素(WebElements)
WebDriver中的定位元素可以在WebDriver实例本身或WebElement上完成。每个语言绑定都公开“查找元素”和“查找元素”方法。前者返回与查询匹配的WebElement 对象 ,如果找不到这样的元素,则抛出异常。后者返回 WebElements 列表,如果没有DOM元素与查询匹配,则可能为空。

“Find”方法采用名为“By”的定位器或查询对象。“By”策略列在下面。


By ID
这是定位元素的最有效和首选方式。UI开发人员常见的缺陷是在页面上具有非唯一ID或自动生成id,两者都应该避免。html元素上的类比自动生成的id更合适。

如何查找如下所示元素的示例:
<div id="coolestWidgetEvah">...</div>
java
WebElement element = driver.findElement(By.id("coolestWidgetEvah"));
csharp
IWebElement element = driver.FindElement(By.Id("coolestWidgetEvah"));
ruby
element = driver.find_element(:id, "coolestWidgetEvah")
python
element = driver.find_element_by_id("coolestWidgetEvah")
or
from selenium.webdriver.common.by import By
element = driver.find_element(by=By.ID, value="coolestWidgetEvah")
perl
$element = $driver->find_element('coolestWidgetEvah','id')
javascript
var element = driver.findElement(By.id('coolestWidgetEvah'));

By Class Name
在这种情况下,“Class”是指DOM元素上的属性。通常在实际使用中有许多具有相同类名的DOM元素,因此找到多个元素变得比找到第一个元素更实用。

如何查找如下所示元素的示例:
<div class="cheese"><span>Cheddar</span></div><div class="cheese"><span>Gouda</span></div>
java
List<WebElement> cheeses = driver.findElements(By.className("cheese"));
csharp
IList<IWebElement> cheeses = driver.FindElements(By.ClassName("cheese"));
ruby
cheeses = driver.find_elements(:class_name, "cheese")
or
cheeses = driver.find_elements(:class, "cheese")
python
cheeses = driver.find_elements_by_class_name("cheese")
or
from selenium.webdriver.common.by import By
cheeses = driver.find_elements(By.CLASS_NAME, "cheese")
perl
@cheeses = $driver->find_elements('cheese', 'class');
javascript
driver.findElements(By.className("cheese"))
.then(cheeses => console.log(cheeses.length));


By Tag Name
 DOM标签元素的名称。如何查找如下所示元素的示例:

<iframe src="..."></iframe>
java
WebElement frame = driver.findElement(By.tagName("iframe"));
csharp
IWebElement cheese = driver.FindElement(By.Name("cheese"));
ruby
cheese = driver.find_element(:name, "cheese")
python
cheese = driver.find_element_by_name("cheese")
or
from selenium.webdriver.common.by import By
cheese = driver.find_element(By.NAME, "cheese")
perl
$cheese = $driver->find_element('cheese', 'name');
javascript
var cheese = driver.findElement(By.name('cheese'));

By Name 找到具有匹配name属性的input元素。
如何查找如下所示元素的示例:
<input name="cheese" type="text"/>
java
WebElement cheese = driver.findElement(By.name("cheese"));
csharp
IWebElement cheese = driver.FindElement(By.Name("cheese"));
ruby
cheese = driver.find_element(:name, "cheese")
python
cheese = driver.find_element_by_name("cheese")
or
from selenium.webdriver.common.by import By
cheese = driver.find_element(By.NAME, "cheese")
perl
$cheese = $driver->find_element('cheese', 'name');
javascript
var cheese = driver.findElement(By.name('cheese'));

By Link Text
找到具有匹配可见文本的link元素。

如何查找如下所示元素的示例:
<a href="http://www.google.com/search?q=cheese">cheese</a>>
java
WebElement cheese = driver.findElement(By.linkText("cheese"));
csharp
IWebElement cheese = driver.FindElement(By.LinkText("cheese"));
ruby
cheese = driver.find_element(:link_text, "cheese")

or

cheese = driver.find_element(:link, "cheese")
python
cheese = driver.find_element_by_link_text("cheese")

or

from selenium.webdriver.common.by import By
cheese = driver.find_element(By.LINK_TEXT, "cheese")
perl
$cheese = $driver->find_element('cheese', 'link_text');
javascript
var cheese = driver.findElement(By.linkText('cheese'));

By Partial Link Text
找到部分匹配可见文本的链接元素。

如何查找如下所示元素的示例:

<a href="http://www.google.com/search?q=cheese">search for cheese</a>>
java
WebElement cheese = driver.findElement(By.partialLinkText("cheese"));
csharp
IWebElement cheese = driver.FindElement(By.PartialLinkText("cheese"));
ruby
cheese = driver.find_element(:partial_link_text, "cheese")
python
cheese = driver.find_element_by_partial_link_text("cheese")
or
from selenium.webdriver.common.by import By
cheese = driver.find_element(By.PARTIAL_LINK_TEXT, "cheese")
perl
$cheese = $driver->find_element('cheese', 'partial_link_text');
javascript
var cheese = driver.findElement(By.partialLinkText('cheese'));

By CSS
就像名字暗示它是css的定位策略。
默认情况下使用本机浏览器支持,因此请参阅w3c css选择器以获取通常可用的css选择器列表。如果浏览器没有css查询的本机支持,则使用Sizzle。IE 6,7和FF3.0目前使用Sizzle作为css查询引擎。

请注意,并非所有浏览器都是相同的,一些可能在一个版本中工作的CSS可能在另一个版本中不起作用。

找到下面的cheese的例子:

<div id="food"><span class="dairy">milk</span><span class="dairy aged">cheese</span></div>
java
WebElement cheese = driver.findElement(By.cssSelector("#food span.dairy.aged"));
csharp
IWebElement cheese = driver.FindElement(By.CssSelector("#food span.dairy.aged"));
ruby
cheese = driver.find_element(:css, "#food span.dairy.aged")
python
cheese = driver.find_element_by_css_selector("#food span.dairy.aged")
or
from selenium.webdriver.common.by import By
cheese = driver.find_element(By.CSS_SELECTOR, "#food span.dairy.aged")
perl
$cheese = $driver->find_element('#food span.dairy.aged', 'css');
javascript
var cheese = driver.findElement(By.css('#food span.dairy.aged'));

By XPath
在较高的层面上,WebDriver尽可能使用浏览器的本机XPath功能。
在那些没有本机XPath支持的浏览器上,我们提供了自己的实现。除非您了解各种XPath引擎中的差异,否则这可能会导致一些意外行为。

 


这有点抽象,所以对于下面的HTML:
<input type="text" name="example" />
<INPUT type="text" name="other" />
java
List<WebElement> inputs = driver.findElements(By.xpath("//input"));
IList<IWebElement> inputs = driver.FindElements(By.XPath("//input"));
ruby
inputs = driver.find_elements(:xpath, "//input")
python
inputs = driver.find_elements_by_xpath("//input")
or
from selenium.webdriver.common.by import By
inputs = driver.find_elements(By.XPATH, "//input")
perl
@inputs = $driver->find_elements('//input')
javascript
driver.findElements(By.xpath("//input"))
.then(cheeses => console.log(cheeses.length));


将找到以下匹配数量
 
XPath表达式    HtmlUnit驱动程序    Firefox驱动程序    Internet Explorer驱动程序
//输入    1(“例子”)    2    2
// INPUT    0    2    0
有时,HTML元素不需要显式声明属性,因为它们将默认为已知值。例如,“input”标记不需要“type”属性,因为它默认为“text”。在WebDriver中使用xpath时的经验法则是,您不应期望能够匹配这些隐式属性。

使用JavaScript
您可以执行任意javascript来查找元素,只要返回DOM元素,它就会自动转换为WebElement对象。

加载jQuery的页面上的简单示例:

java
WebElement element = (WebElement) ((JavascriptExecutor)driver).executeScript("return $('.cheese')[0]");
csharp
IWebElement element = (IWebElement) ((IJavaScriptExecutor)driver).ExecuteScript("return $('.cheese')[0]");
ruby
element = driver.execute_script("return $('.cheese')[0]")
python
element = driver.execute_script("return $('.cheese')[0]")
perl
element = $driver->execute_script("return $('.cheese')[0]");

查找页面上每个标签的所有输入元素:
java
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);
csharp
IList<IWebElement> labels = driver.FindElements(By.TagName("label"));
IList<IWebElement> inputs = (IList<IWebElement>) ((IJavaScriptExecutor)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);
ruby
labels = driver.find_elements(:tag_name, "label")
inputs = driver.execute_script(
    "var labels = arguments[0], inputs = []; for (var i=0; i < labels.length; i++){" +
    "inputs.push(document.getElementById(labels[i].getAttribute('for'))); } return inputs;", labels)
python
labels = driver.find_elements_by_tag_name("label")
inputs = driver.execute_script(
    "var labels = arguments[0], inputs = []; for (var i=0; i < labels.length; i++){" +
    "inputs.push(document.getElementById(labels[i].getAttribute('for'))); } return inputs;", labels)
perl
my @labels = $driver->find_elements('label', 'tag_name');
my $inputs = $driver->execute_script("var labels = arguments, inputs = []; for (var i=0; i < labels.length; i++){ inputs.push(document.getElementById(labels[i].getAttribute('for'))); } return inputs;", @labels);

Getting text values
获取文本值
人们通常希望检索元素中包含的innerText值。这将返回单个字符串值。请注意,这只会返回页面上显示的可见文本。

java
WebElement element = driver.findElement(By.id("elementID"));
element.getText();
csharp
IWebElement element = driver.findElement(By.id("elementID"));
element.Text;
ruby
element = driver.find_element :id => "element_id"
element.text
python
element = driver.find_element_by_id("element_id")
element.text
javascript
var element = driver.findElement(By.id('elementID'));
element.getText().then(text => console.log(`Text is ${text}`));

User Input - Filling In Forms
用户输入 - 填写表单
我们已经看过如何在textarea或text字段中输入文本,但其他元素呢?您可以“切换”复选框的状态,也可以使用“单击”设置选择的OPTION标记。处理SELECT标签也不错:
java
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();
}
csharp
IWebElement select = driver.FindElement(By.TagName("select"));
IList<IWebElement> allOptions = select.FindElements(By.TagName("option"));
foreach (IWebElement option in allOptions)
{
    Console.WriteLine("Value is: " + option.GetAttribute("value"));
    option.Click();
}
ruby
select = driver.find_element(:tag_name, "select")
all_options = select.find_elements(:tag_name, "option")
all_options.each do |option|
  puts "Value is: " + option.attribute("value")
  option.click
end
python
select = driver.find_element_by_tag_name("select")
allOptions = select.find_elements_by_tag_name("option")
for option in allOptions:
    print "Value is: " + option.get_attribute("value")
    option.click()
perl
$select = $driver->find_element('select', 'tag_name');
@allOptions = $driver->find_child_element($select, "option", 'tag_name');
foreach $option (@allOptions){
    print "Value is: ".$option->get_attribute("value")."\n";
    $option->click();
}

这将在页面上找到第一个“SELECT”元素,依次循环遍历每个OPTION,打印出它们的值,然后依次选择每个OPTION。正如您将注意到的,这不是处理SELECT元素的最有效方法。WebDriver的支持类包括一个名为“Select”的支持类,它提供了与这些类交互的有用方法。

java
Select select = new Select(driver.findElement(By.tagName("select")));
select.deselectAll();
select.selectByVisibleText("Edam");
csharp
SelectElement select = new SelectElement(driver.FindElement(By.TagName("select")));
select.DeselectAll();
select.SelectByText("Edam");
ruby
# available since 2.14
    select = Selenium::WebDriver::Support::Select.new(driver.find_element(:tag_name, "select"))
    select.deselect_all()
    select.select_by(:text, "Edam")
python
# available since 2.12
from selenium.webdriver.support.ui import Select
select = Select(driver.find_element_by_tag_name("select"))
select.deselect_all()
select.select_by_visible_text("Edam")

This will deselect all OPTIONs from the first SELECT on the page, and then select the OPTION with the displayed text of “Edam”.
Once you’ve finished filling out the form, you probably want to submit it. One way to do this would be to find the “submit” button and click it:
这将从页面上的第一个SELECT中取消选择所有OPTION,然后选择带有显示文本“Edam”的OPTION。
填写完表单后,您可能想要提交表单。一种方法是找到“提交”按钮并单击它:

java
driver.findElement(By.id("submit")).click();
csharp
driver.FindElement(By.Id("submit")).Click();
ruby
driver.find_element(:id, "submit").click
python
driver.find_element_by_id("submit").click()
perl
$driver->find_element('submit','id')->click()
javascript
driver.findElement(By.id('submit').click();

Alternatively, WebDriver has the convenience method “submit” on every element. If you call this on an element within a form, WebDriver will walk up the DOM until it finds the enclosing form and then calls submit on that. If the element isn’t in a form, then the NoSuchElementException will be thrown:
或者,WebDriver在每个元素上都有“提交”的便捷方法。如果在表单中的元素上调用它,WebDriver将向上走DOM,直到找到封闭的表单,然后调用submit。如果元素不在表单中,那么NoSuchElementException将抛出:

java
element.submit();
csharp
element.Submit();
ruby
element.submit
python
element.submit()
perl
$element->submit()
javascript
element.submit();

Moving Between Windows and Frames
在Windows和框架之间移动
某些Web应用程序具有许多帧或多个窗口。WebDriver支持使用“switchTo”方法在命名窗口之间移动:

java
driver.switchTo().window("windowName");
csharp
driver.SwitchTo().Window("windowName");
ruby
driver.switch_to.window("windowName")
python
driver.switch_to.window("windowName")
perl
$driver->switch_to_window("windowName");
javascript
driver.switchTo().window('windowName');

All calls to driver will now be interpreted as being directed to the particular window. But how do you know the window’s name? Take a look at the javascript or link that opened it:
所有调用driver现在将被解释为定向到特定窗口。但你怎么知道窗口的名字?看一下打开它的javascript或链接:

<a href="somewhere.html" target="windowName">Click here to open a new window</a>
或者,您可以将“窗口句柄”传递给“switchTo()。window()”方法。知道这一点,就可以迭代每个打开的窗口,如下所示:

java
for (String handle : driver.getWindowHandles()) {
    driver.switchTo().window(handle);
}
csharp
foreach (string handle in driver.WindowHandles) {
    driver.SwitchTo().Window(handle);
}
ruby
driver.window_handles.each do |handle|
    driver.switch_to.window handle
end
python
for handle in driver.window_handles:
    driver.switch_to.window(handle)
perl
$windows = $driver->get_window_handles()
foreach $window (@$windows){
    $driver->switch_to_window($window);
}

You can also switch from frame to frame (or into iframes):
您还可以从一帧切换到另一帧(或切换到iframe):

java
driver.switchTo().frame("frameName");
csharp
driver.SwitchTo().Frame("frameName");
ruby
driver.switch_to.frame "frameName"
python
driver.switch_to.frame("frameName")
perl
$driver->switch_to_frame('frameName');
javascript
driver.switchTo().frame('frameName');

Popup Dialogs
弹出对话框
从Selenium 2.0 beta 1开始,内置支持处理弹出对话框。触发打开弹出窗口的操作后,您可以使用以下命令访问警报:

java
Alert alert = driver.switchTo().alert();
csharp
Alert alert = driver.SwitchTo().Alert();
ruby
alert = driver.switch_to.alert
python
alert = driver.switch_to.alert
# usage: alert.dismiss(), etc.
perl
$driver->get_alert_text();
$driver->accept_alert();
javascript
var alert = driver.switchTo().alert();
alert.accept();


这将返回当前打开的警报对象。使用此对象,您现在可以接受,关闭,读取其内容,甚至可以键入提示。此界面在警报,确认和提示方面同样有效。有关更多信息,请参阅JavaDocs 或RubyDocs。

Navigation: History and Location
导航:历史和位置
之前,我们介绍了使用“get”命令(driver.get("http://www.example.com")或driver.Url="http://www.example.com"在C#中)导航到页面 。正如您所见,WebDriver具有许多较小的,以任务为中心的界面,导航是一项有用的任务。因为加载页面是一个基本要求,所以这样做的方法存在于主WebDriver接口上,但它只是一个同义词:

java
driver.navigate().to("http://www.example.com");
csharp
driver.Navigate().GoToUrl("http://www.example.com");
ruby
driver.navigate.to "http://www.example.com"
python
driver.get("http://www.example.com")  # python doesn't have driver.navigate
perl
$driver->navigate('http://www.example.com');
javascript
driver.navigate().to('http://www.example.com');


重申:“ navigate().to()”和“ get()”做同样的事情。一个比另一个更容易打字!

The “navigate” interface also exposes the ability to move backwards and forwards in your browser’s history:
“导航”界面还提供了在浏览器历史记录中前后移动的功能:

java
driver.navigate().forward();
driver.navigate().back();
csharp
driver.Navigate().Forward();
driver.Navigate().Back();
ruby
driver.navigate.forward
driver.navigate.back
python
driver.forward()
driver.back()
javascript
driver.navigate().forward();
driver.navigate().back();

请注意,此功能完全取决于底层浏览器。如果您习惯于一个浏览器的行为而不是另一个浏览器,那么当您调用这些方法时,可能会发生意外情况。

Cookies
在我们离开这些后续步骤之前,您可能有兴趣了解如何使用cookie。首先,您需要在cookie有效的域上。如果您在开始与网站交互之前尝试预设Cookie并且您的主页很大/需要一段时间来加载替代方法是在网站上找到一个较小的页面(通常404页面很小,例如http:// example .com / some404page)。

java
// Go to the correct domain
driver.get("http://www.example.com");

// Now set the cookie. This one's valid for the entire domain
Cookie cookie = new Cookie("key", "value");
driver.manage().addCookie(cookie);

// And now output all the available cookies for the current URL
Set<Cookie> allCookies = driver.manage().getCookies();
for (Cookie loadedCookie : allCookies) {
    System.out.println(String.format("%s -> %s", loadedCookie.getName(), loadedCookie.getValue()));
}

// You can delete cookies in 3 ways
// By name
driver.manage().deleteCookieNamed("CookieName");
// By Cookie
driver.manage().deleteCookie(loadedCookie);
// Or all of them
driver.manage().deleteAllCookies();
python
# Go to the correct domain
driver.get("http://www.example.com")

# Now set the cookie. Here's one for the entire domain
# the cookie name here is 'key' and its value is 'value'
driver.add_cookie({'name':'key', 'value':'value', 'path':'/'})
# additional keys that can be passed in are:
# 'domain' -> String,
# 'secure' -> Boolean,
# 'expiry' -> Milliseconds since the Epoch it should expire.

# And now output all the available cookies for the current URL
for cookie in driver.get_cookies():
    print "%s -> %s" % (cookie['name'], cookie['value'])

# You can delete cookies in 2 ways
# By name
driver.delete_cookie("CookieName")
# Or all of them
driver.delete_all_cookies()
ruby
# Go to the correct domain
driver.get "http://www.example.com"

# Now set the cookie. Here's one for the entire domain
# the cookie name here is 'key' and its value is 'value'
driver.manage.add_cookie(:name => 'key', :value => 'value')
# additional keys that can be passed in are:
# :path => String, :secure -> Boolean, :expires -> Time, DateTime, or seconds since epoch

# And now output all the available cookies for the current URL
driver.manage.all_cookies.each { |cookie|
    puts "#{cookie[:name]} => #{cookie[:value]}"
}

# You can delete cookies in 2 ways
# By name
driver.manage.delete_cookie "CookieName"
# Or all of them
driver.manage.delete_all_cookies
perl
# Go to the correct domain
$driver->get("http://www.example.com");

# Now set the cookie. Here's one for the entire domain
# the cookie name here is 'key' and its value is 'value'
$driver->add_cookie('key', 'value', '/', 'example.com', 0);
# additional required inputs are path and domain
# the final input secure is an optional boolean

# And now output all the available cookies for the current URL
my $cookies_ref = $driver->get_all_cookies(); # Returns reference to AoH
for $cookie_ref (@{$cookies_ref}) {
    printf "%s => %s\n", $cookie_ref->{name}, $cookie_ref->{value};
}

# You can delete cookies in 2 ways
# By name
$driver->delete_cookie_named("key");
# Or all of them
$driver->delete_all_cookies();
javascript
# Go to the correct domain
driver.get('http://www.example.com');

# Now set the basic cookie. Here's one for the entire domain
# the cookie name here is 'key' and its value is 'value'
driver.manage().addCookie({name: 'cookie-1', value: 'cookieValue'});

# And now output all the available cookies for the current URL
driver.manage().getCookies().then( (loadedCookies) =>{
    for (let cookie in loadedCookies) {
    console.log('printing Cookies loaded : '+cookie);
    }
    });
# You can delete cookies in 2 ways
# By name
driver.manage().deleteCookie('cookie-1');
# Or all of them
driver.manage().deleteAllCookies();

Changing the User Agent
更改用户代理
使用Firefox驱动程序很容易:
This is easy with the Firefox Driver:

java
FirefoxProfile profile = new FirefoxProfile();
profile.addAdditionalPreference("general.useragent.override", "some UA string");
WebDriver driver = new FirefoxDriver(profile);
csharp
var profile = new FirefoxProfile();
profile.SetPreference("general.useragent.override", "some UA string");
IWebDriver driver = new FirefoxDriver(profile);
ruby
profile = Selenium::WebDriver::Firefox::Profile.new
profile['general.useragent.override'] = "some UA string"
driver = Selenium::WebDriver.for :firefox, :profile => profile
python
profile = webdriver.FirefoxProfile()
profile.set_preference("general.useragent.override", "some UA string")
driver = webdriver.Firefox(profile)
perl
use Selenium::Remote::Driver::Firefox::Profile;
my $profile = Selenium::Remote::Driver::Firefox::Profile->new;
$profile->set_preference('general.useragent.overide' => "some UA string");
my $driver = Selenium::Remote::Driver->new('firefox_profile' => $profile);

Drag And Drop
拖放
这是使用Actions类执行拖放的示例。需要启用本机事件。

java
WebElement element = driver.findElement(By.name("source"));
WebElement target = driver.findElement(By.name("target"));

(new Actions(driver)).dragAndDrop(element, target).perform();
csharp
IWebElement element = driver.FindElement(By.Name("source"));
IWebElement target = driver.FindElement(By.Name("target"));
(new Actions(driver)).DragAndDrop(element, target).Perform();
ruby
element = driver.find_element(:name => 'source')
target = driver.find_element(:name => 'target')

driver.action.drag_and_drop(element, target).perform
python
from selenium.webdriver.common.action_chains import ActionChains
element = driver.find_element_by_name("source")
target =  driver.find_element_by_name("target")

ActionChains(driver).drag_and_drop(element, target).perform()
perl
$element->drag(216,158);

Driver Specifics and Tradeoffs
驱动程序细节和权衡
Selenium-WebDriver的驱动程序
WebDriver是应该编写测试的关键接口的名称,但有几个实现。这些包括:

HtmlUnit驱动程序
这是目前WebDriver最快,最轻量级的实现。顾名思义,这是基于HtmlUnit。HtmlUnit是一个基于Java的WebBrowser实现,没有GUI。对于任何语言绑定(除了java),Selenium Server都需要使用此驱动程序。

用法
java
WebDriver driver = new HtmlUnitDriver();
csharp
IWebDriver driver = new RemoteWebDriver(new Uri("http://127.0.0.1:4444/wd/hub"),
                                        DesiredCapabilities.HtmlUnit());
python
driver = webdriver.Remote("http://localhost:4444/wd/hub", webdriver.DesiredCapabilities.HTMLUNIT.copy())
ruby
driver = Selenium::WebDriver.for :remote, :url => "http://localhost:4444/wd/hub", :desired_capabilities => :htmlunit
perl
my $driver = Selenium::Remote::Driver->new(browser_name => 'htmlunit', remote_server_addr => 'localhost', port => '4444');


Pros
WebDriver的最快实现
纯Java解决方案,因此它与平台无关。
支持JavaScript
缺点
模拟其他浏览器的JavaScript行为(见下文)
JavaScript中的驱动程序的HtmlUnit
没有一种流行的浏览器使用HtmlUnit(Rhino)使用的JavaScript引擎。如果您使用HtmlUnit测试JavaScript,结果可能与这些浏览器有很大不同。

当我们说“JavaScript”时,我们实际上是指“JavaScript和DOM”。虽然DOM是由W3C定义的,但每个浏览器都有自己的怪癖和DOM实现的差异以及JavaScript与它的交互方式。HtmlUnit有一个令人印象深刻的完整DOM实现,并且对使用JavaScript有很好的支持,但它与任何其他浏览器没什么不同:它有自己的怪癖和W3C标准和主要浏览器的DOM实现的差异,尽管它能够模仿其他浏览器。

使用WebDriver,我们必须做出选择; 我们是否支持HtmlUnit的JavaScript功能,并冒着团队遇到问题的风险,这些问题只能在那里显现,或者我们是否禁用JavaScript,因为我们知道有越来越多的网站依赖JavaScript?我们采用了保守的方法,默认情况下在使用HtmlUnit时禁用了支持。随着WebDriver和HtmlUnit的每次发布,我们重新评估这个决定:我们希望在某些时候默认在HtmlUnit上启用JavaScript。

启用JavaScript
如果您迫不及待,启用JavaScript支持非常简单:

java
HtmlUnitDriver driver = new HtmlUnitDriver(true);
csharp
WebDriver driver = new RemoteWebDriver(new Uri("http://127.0.0.1:4444/wd/hub"),
                       DesiredCapabilities.HtmlUnitWithJavaScript());
ruby
caps = Selenium::WebDriver::Remote::Capabilities.htmlunit(:javascript_enabled => true)
driver = Selenium::WebDriver.for :remote, :url => "http://localhost:4444/wd/hub", :desired_capabilities => caps
python
driver = webdriver.Remote("http://localhost:4444/wd/hub", webdriver.DesiredCapabilities.HTMLUNITWITHJS)
perl
$driver = new Selenium::Remote::Driver( browser_name=>'firefox', port=> 4444, version=>'', platform=>'LINUX', javascript=>1, auto_close=>1);

这将导致HtmlUnit驱动程序默认模拟Firefox 3.6的JavaScript处理。

Firefox驱动程序
使用Firefox插件控制Firefox浏览器。使用的Firefox配置文件从计算机上安装的内容中删除,仅包含Selenium WebDriver.xpi(插件)。默认情况下也会更改一些设置(请参阅参考资料以查看哪些设置)Firefox驱动程序能够运行并在Windows,Mac,Linux上进行测试。目前在版本3.6,10,最新 - 1,最新

用法
java
WebDriver driver = new FirefoxDriver();
csharp
IWebDriver driver = new FirefoxDriver();
python
driver = webdriver.Firefox()
ruby
driver = Selenium::WebDriver.for :firefox
perl
my $driver = Selenium::Remote::Driver->new;

Pros专业
在真实的浏览器中运行并支持JavaScript
比Internet Explorer驱动程序更快
缺点
比HtmlUnit驱动程序慢

修改Firefox配置文件
假设您想要修改用户代理字符串(如上所述),但您已经获得了一个包含许多有用扩展的Firefox配置文件。有两种方法可以获取此配置文件。假设已使用Firefox的配置文件管理器()创建了配置文件:firefox -ProfileManager

java
ProfilesIni allProfiles = new ProfilesIni();
FirefoxProfile profile = allProfiles.getProfile("WebDriver");
profile.setPreferences("foo.bar", 23);
WebDriver driver = new FirefoxDriver(profile);
csharp
var profileManager = new FirefoxProfileManager();
FirefoxProfile profile = profileManager.GetProfile("WebDriver");
profile.SetPreference("foo.bar", 23);
IWebDriver driver = new FirefoxDriver(profile);
Alternatively, if the profile isn’t already registered with Firefox:

java
File profileDir = new File("path/to/top/level/of/profile");
FirefoxProfile profile = new FirefoxProfile(profileDir);
profile.addAdditionalPreferences(extraPrefs);
WebDriver driver = new FirefoxDriver(profile);
csharp
FirefoxProfile profile = new FirefoxProfile("path/to/top/level/of/profile");
profile.SetPreference("extra", "pref");
IWebDriver driver = new FirefoxDriver(profile);


或者,如果配置文件尚未在Firefox中注册:
Alternatively, if the profile isn’t already registered with Firefox:

java
File profileDir = new File("path/to/top/level/of/profile");
FirefoxProfile profile = new FirefoxProfile(profileDir);
profile.addAdditionalPreferences(extraPrefs);
WebDriver driver = new FirefoxDriver(profile);
csharp
FirefoxProfile profile = new FirefoxProfile("path/to/top/level/of/profile");
profile.SetPreference("extra", "pref");
IWebDriver driver = new FirefoxDriver(profile);

As we develop features in the Firefox Driver, we expose the ability to use them. For example, until we feel native events are stable on Firefox for Linux, they are disabled by default. To enable them:
当我们在Firefox驱动程序中开发功能时,我们会公开使用它们的能力。例如,在我们认为Firefox for Linux上的本机事件稳定之前,默认情况下会禁用它们。要启用它们:

java
FirefoxProfile profile = new FirefoxProfile();
profile.setEnableNativeEvents(true);
WebDriver driver = new FirefoxDriver(profile);
csharp
var profile = new FirefoxProfile {EnableNativeEvents = true};
IWebDriver driver = new FirefoxDriver(profile);
python
profile = webdriver.FirefoxProfile()
profile.native_events_enabled = True
driver = webdriver.Firefox(profile)
ruby
profile = Selenium::WebDriver::Firefox::Profile.new
profile.native_events = true
driver = Selenium::WebDriver.for :firefox, :profile => profile


信息
有关最新信息,请参阅Wiki页面中的Firefox部分。

Internet Explorer驱动程序
InternetExplorerDriver是一个独立的服务器,它实现了WebDriver的有线协议。此驱动程序已在适用于Vista,Windows 7,Windows 8和Windows 8.1的组合上使用IE 7,8,9,10和11进行了测试。截至2014年4月15日,不再支持IE 6。

该驱动程序支持运行32位和64位版本的浏览器。选择如何确定在启动浏览器时使用哪个“bit-ness”取决于启动哪个版本的IEDriverServer.exe。如果启动32位版本的IEDriverServer.exe,将启动32位版本的IE。同样,如果启动64位版本的IEDriverServer.exe,将启动64位版本的IE。

java
WebDriver driver = new InternetExplorerDriver();
csharp
IWebDriver driver = new InternetExlorerDriver();
python
driver = webdriver.Ie()
ruby
driver = Selenium::WebDriver.for :ie
perl
my $driver = Selenium::Remote::Driver->new(browser_name => 'internet explorer');

Pros
专业
在真实的浏览器中运行并支持Javascript
缺点
显然InternetExplorerDriver只能在Windows上运行!
比较慢(虽然还很漂亮!)
信息
有关最新信息,请参阅Wiki页面的Internet Explorer部分。请特别注意“必需配置”部分。

ChromeDriver
ChromeDriver由Chromium 项目iteslf 维护/支持。WebDriver通过chromedriver二进制文件与Chrome一起使用(可在chrome项目的下载页面上找到)。您需要安装chromedriver和Chrome浏览器版本。chromedriver需要放在系统路径的某个位置,以便WebDriver自动发现它。Chrome浏览器本身是由chromedriver在默认安装路径中发现的。这两者都可以被环境变量覆盖。 有关更多信息,请参阅维基。

用法
Usage
java
WebDriver driver = new ChromeDriver();
csharp
IWebDriver driver = new ChromeDriver();
python
driver = webdriver.Chrome()
ruby
driver = Selenium::WebDriver.for :chrome
perl
my $driver = Selenium::Remote::Driver->new(browser_name => 'chrome');

Pros
专业
在真实的浏览器中运行并支持JavaScript
由于Chrome是基于Webkit的浏览器,ChromeDriver可能允许您验证您的网站是否可以在Safari中使用。请注意,由于Chrome使用自己的V8 JavaScript引擎而不是Safari的Nitro引擎,因此JavaScript执行可能会有所不同。
缺点
比HtmlUnit驱动程序慢
信息
有关最新信息,请参阅我们的维基。更多信息也可以在下载页面上找到

使用ChromeDriver运行
下载ChromeDriver可执行文件, 然后按照Wiki页面上的其他说明进行操作

Opera驱动程序
有关使用Opera驱动程序的信息,请参阅Selenium Wiki中的Opera Driver wiki文章。

iOS驱动
查看ios-driver或appium项目。

Android驱动
查看Selendroid项目

备用后端:混合WebDriver和RC技术
WebDriver-Backed Selenium-
Web版本的WebDriver提供了Selenium-RC API的实现。这意味着您可以使用Selenium-RC API使用底层WebDriver技术。这主要是为了向后兼容。它允许那些使用Selenium-RC API的现有测试套件的人使用WebDriver。它旨在帮助简化到Selenium-WebDriver的迁移路径。此外,这允许在同一测试代码中并排使用两个API。

Selenium-WebDriver使用如下:
java
// You may use any WebDriver implementation. Firefox is used here as an example
WebDriver driver = new FirefoxDriver();

// A "base url", used by selenium to resolve relative URLs
 String baseUrl = "http://www.google.com";

// Create the Selenium implementation
Selenium selenium = new WebDriverBackedSelenium(driver, baseUrl);

// Perform actions with selenium

selenium.open("http://www.google.com");
selenium.type("name=q", "cheese");
selenium.click("name=btnG");

// Get the underlying WebDriver implementation back. This will refer to the
// same WebDriver instance as the "driver" variable above.
WebDriver driverInstance = ((WebDriverBackedSelenium) selenium).getWrappedDriver();

//Finally, close the browser. Call stop on the WebDriverBackedSelenium instance
//instead of calling driver.quit(). Otherwise, the JVM will continue running after
//the browser has been closed.
selenium.stop();


专业
允许WebDriver和Selenium API并排生活
为从Selenium RC API到WebDriver的托管迁移提供了一种简单的机制
不需要运行独立的Selenium RC服务器
缺点

不实现每个方法

更高级的Selenium使用(使用“browserbot”或Selenium Core的其他内置JavaScript方法)可能无效
由于底层实现差异,某些方法可能会更慢

Backing WebDriver with Selenium
WebDriver不支持与Selenium RC一样多的浏览器,因此为了在使用WebDriver API时提供该支持,您可以使用 SeleneseCommandExecutor

使用以下代码以这种方式支持Safari(确保禁用弹出窗口阻止):

java
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setBrowserName("safari");
CommandExecutor executor = new SeleneseCommandExecutor(new URL("http://localhost:4444/"), new URL("http://www.google.com/"), capabilities);
WebDriver driver = new RemoteWebDriver(executor, capabilities);
目前这种方法存在一些主要限制,特别是findElements不能按预期工作。此外,因为我们使用Selenium Core来驱动浏览器,所以您受限于JavaScript沙箱。

Running Standalone Selenium Server for use with RemoteDrivers
运行独立的Selenium Server以与RemoteDrivers一起使用
从Selenium的下载页面下载selenium-server-standalone- <version> .jar和可选的IEDriverServer。如果您打算使用Chrome,请从Google Code下载。

解压缩IEDriverServer和/或chromedriver并将它们放在$ PATH /%PATH%上的目录中 - 然后Selenium Server应该能够处理IE / Chrome的请求而无需进行其他修改。

使用命令行启动服务器

java -jar <path_to>/selenium-server-standalone-<version>.jar
如果要使用本机事件功能,请在命令行上使用该选项指明此功能

-Dwebdriver.enable.native.events=1
对于其他命令行选项,请执行

java -jar <path_to>/selenium-server-standalone-<version>.jar -help
为了正常运行,应允许以下端口进入TCP连接:4444,7054-5(或者是您计划运行的并发实例数的两倍)。在Windows下,您可能还需要取消阻止应用程序。

其他资源
您可以在WebDriver的wiki中找到WebDriver的更多资源

当然,不要犹豫,在任何Selenium主题上进行互联网搜索,包括Selenium-WebDriver的驱动程序。Selenium上有很多博客以及各种用户论坛上的大量帖子。此外,Selenium用户组是一个很好的资源。 http://groups.google.com/group/selenium-users

后续步骤
本章简单介绍了WebDriver及其一些关键功能的高级演练。熟悉Selenium-WebDriver API后,您将学习如何在AUT的功能经常更改时构建测试套件,以实现可维护性,可扩展性和降低的脆弱性。大多数Selenium专家现在推荐的方法是使用页面对象设计模式以及可能的页面工厂来设计测试代码。Selenium-WebDriver通过在Java和C#中提供PageFactory类来为此提供支持。在下一章中将介绍这些以及其他高级主题 。此外,对于此技术的高级描述,您可能需要查看“ 测试设计注意事项”一章。这两章都介绍了通过使测试代码更加模块化来编写更易维护的测试的技术。

原文地址

https://www.seleniumhq.org/docs/03_webdriver.jsp#how-does-webdriver-drive-the-browser-compared-to-selenium-rc

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值