溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Selenium官文翻譯--(二)Selenium WebDriver(未完待續(xù))

發(fā)布時間:2020-05-26 16:32:26 來源:網(wǎng)絡(luò) 閱讀:839 作者:honzhang 欄目:web開發(fā)

NOTE: We’re currently working on documenting these sections. We believe the information here is accurate, however be aware we are also still working on this chapter. Additional information will be provided as we go which should make this chapter more solid.

我們目前需要使用這部分的文檔來工作,我們相信這里的信息都是正確。附加信息將會使這部分的內(nèi)容更加堅實。

Introducing WebDriver

The primary new feature in Selenium 2.0 is the integration of the WebDriver API. WebDriver is designed to provide a simpler, more concise programming interface in addition to addressing some 

一些初級的新的特性在2.0中是集成在WebDriver  API中的。 Webdriver會提供一個簡便的、更簡潔的編程接口,除了處理一些限制的API。

limitations in the Selenium-RC API. Selenium-WebDriver was developed to better support dynamic web pages where elements of a page may change without the page itself being reloaded.

Selenium-WebDriver是為了更好地支持開發(fā)動態(tài)web頁面,頁面元素沒有被重新加載頁面本身可能會改變。

 WebDriver’s goal is to supply a well-designed object-oriented API that provides improved support for modern advanced web-app testing problems.

WebDriver的目標(biāo)是提供一個精心設(shè)計的面向?qū)ο蟮腁PI,提供了現(xiàn)代先進(jìn)的web測試問題改進(jìn)的支持。

How Does WebDriver ‘Drive’ the Browser Compared to Selenium-RC?

Selenium-WebDriver makes direct calls to the browser using each browser’s native support for automation. How these direct calls are made, and the features they support depends on the 

Selenium-WebDriver使直接調(diào)用瀏覽器使用每個瀏覽器的本地支持自動化。如何將這些直接調(diào)用,和它們所支持的特性取決于您所使用的瀏覽器。

browser you are using. Information on each ‘browser driver’ is provided later in this chapter.

每個瀏覽器的司機(jī)的信息在本章后面提供。每個瀏覽器的驅(qū)動信息將在后邊章節(jié)中提供。

For those familiar with Selenium-RC, this is quite different from what you are used to. Selenium-RC worked the same way for each supported browser. It ‘injected’ javascript functions into the

對于那些熟悉selenium rc,這是完全不同于你所使用過的。selenium rc為每個受支持的瀏覽器以同樣的方式工作。

 browser when the browser was loaded and then used its javascript to drive the AUT within the browser. WebDriver does not use this technique. Again, it drives the browser directly using the 

它“注入”javascript函數(shù)到瀏覽器當(dāng)瀏覽器加載,然后利用其javascript驅(qū)動AUT中瀏覽器。WebDriver 不使用這些技術(shù)。再有, 它直接驅(qū)動瀏覽器使用瀏覽器自動支持編譯。

browser’s built in support for automation.

WebDriver and the Selenium-Server

You may, or may not, need the Selenium Server, depending on how you intend to use Selenium-WebDriver. If you will be only using the WebDriver API you do not need the Selenium-Server. If your browser and tests will all run on the same machine, and your tests only use the WebDriver API, then you do not need to run the Selenium-Server; WebDriver will run the browser directly.

There are some reasons though to use the Selenium-Server with Selenium-WebDriver.

  • You are using Selenium-Grid to distribute your tests over multiple machines or virtual machines (VMs).

  • 您正在使用selenium grid將測試分配到多臺機(jī)器上或虛擬機(jī)(vm)。

  • You want to connect to a remote machine that has a particular browser version that is not on your current machine.

你想要連接到遠(yuǎn)程計算機(jī),一個特定的瀏覽器版本,不是你現(xiàn)在的機(jī)器上。

  • You are not using the Java bindings (i.e. Python, C#, or Ruby) and would like to use HtmlUnit Driver

  • 你不使用Java綁定(例如Python,c#或Ruby),愿用HtmlUnit驅(qū)動。

Setting Up a Selenium-WebDriver Project


To install Selenium means to set up a project in a development so you can write a program using Selenium. How you do this depends on your programming language and your development environment.

安裝Selenium意味著建立一個項目在 開發(fā)工具,這樣你可以使用Selenium寫一個程序。你如何做到這一點取決于你的編程語言和開發(fā)環(huán)境。

Java

The easiest way to set up a Selenium 2.0 Java project is to use Maven. Maven will download the java bindings (the Selenium 2.0 java client library) and all its dependencies, and will create the 

最容易的方法是建立一個Selenium2.0java項目用Maven.Maven將下載java綁定(Selenium2.0 java客戶端庫)及其所有依賴項。并將為你創(chuàng)建一個項目,用Maven pom.xml (project configuration) file.

project for you, using a maven pom.xml (project configuration) file. Once you’ve done this, you can import the maven project into your preferred IDE, IntelliJ IDEA or Eclipse.

一旦你這樣做,你可以將maven項目導(dǎo)入到你喜歡的IDE,IntelliJ IDEA或Eclipse。

First, create a folder to contain your Selenium project files. Then, to use Maven, you need a pom.xml file. This can be created with a text editor. We won’t teach the details of pom.xml files or for 

首先, 創(chuàng)建一個文件夾包含你的Selenium項目文件 。 然后,你用Maven ,你需要一個pom.xml file。 這將創(chuàng)建一個文本編輯器,我們會提供一些 細(xì)節(jié)針對pom.xml files

using Maven since there are already excellent references on this. Your pom.xml file will look something like this. Create this file in the folder you created for your project.

使用Maven,因為已經(jīng)有很好的參考。xml文件將會看起來像這樣。創(chuàng)建這個文件在您為您的項目創(chuàng)建的文件夾。

<?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-java</artifactId>
                <version>2.53.0</version>
            </dependency>
            <dependency>
                <groupId>org.seleniumhq.selenium</groupId>
                <artifactId>selenium-htmlunit-driver</artifactId>
                <version>2.20</version>
            </dependency>
        </dependencies>
</project>

Be sure you specify the most current version. At the time of writing, the version listed above was the most current, however there were frequent releases immediately after the release of Selenium 2.0. Check the Maven download page for the current release and edit the above dependency accordingly.

確保您指定最新版本。在寫這篇文章的時候,上面列出的版本是最新的,然而之后有頻繁的發(fā)布Selenium .檢查Maven下載頁面的當(dāng)前版本和編輯上述相應(yīng)的依賴.

Now, from a command-line, CD into the project directory and run maven as follows.

現(xiàn)在,從一個命令行,cd命令進(jìn)入項目目錄 并運行Maven按照如下。

mvn clean install

This will download Selenium and all its dependencies and will add them to the project.

這將下載Selenium及其所有依賴項并將它們添加到項目中。

Finally, import the project into your preferred development environment. For those not familiar with this, we’ve provided an appendix which shows this.

最后,將項目導(dǎo)入到您的開發(fā)環(huán)境。對于那些不熟悉這個,我們提供一個顯示了這個附錄。

Importing a maven project into IntelliJ IDEA. Importing a maven project into Eclipse.

Introducing the Selenium-WebDriver API by Example

WebDriver is a tool for automating web application testing, and in particular to verify that they work as expected. It aims to provide a friendly API that’s easy to explore and understand, easier to 

WebDriver是自動化的工具web應(yīng)用程序測試,特別是確認(rèn)他們是否按預(yù)期的方式工作。它旨在提供一個友好的API很容易探索和理解,

use than the Selenium-RC (1.0) API, which will help to make your tests easier to read and maintain. It’s not tied to any particular test framework, so it can be used equally well in a unit testing or 

使之比1.0的API更容易 ,這將有助于使您的測試更容易閱讀和維護(hù)。不與任何特定的測試框架,它同樣可以使用在一個單元測試從一個普通的“主要”方法。

from a plain old “main” method. This section introduces WebDriver’s API and helps get you started becoming familiar with it. Start by setting up a WebDriver project if you haven’t already. 

本節(jié)介紹WebDriver API和幫助你開始熟悉它。首先建立一個WebDriver項目如果你還沒有準(zhǔn)備好。

This was described in the previous section, Setting Up a Selenium-WebDriver Project.

這是在前一節(jié)中描述

Once your project is set up, you can see that WebDriver acts just as any normal library: it is entirely self-contained, and you usually don’t need to remember to start any additional processes or 

一旦設(shè)置您的項目,您可以看到WebDriver行為就像任何正常庫:它是完全獨立的,你通常不需要記住任何額外的流程或開始或

run any installers before using it, as opposed to the proxy server with Selenium-RC.

運行安裝程序之前使用它,而不是與selenium rc代理服務(wù)器。

Note: additional steps are required to use ChromeDriver, Opera Driver, Android Driver and iOS Driver

You’re now ready to write some code. An easy way to get started is this example, which searches for the term “Cheese” on Google and then outputs the result page’s title to the console.

你現(xiàn)在準(zhǔn)備編寫一些代碼。一個簡單的方法開始是這個例子中,這在谷歌上搜索“奶酪”這個詞,然后輸出結(jié)果頁面的標(biāo)題到控制臺。

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();
    }
}

In upcoming sections, you will learn more about how to use WebDriver for things such as navigating forward and backward in your browser’s history, and how to test web sites that use frames and windows. We also provide a more thorough discussions and examples.

在接下來的部分中,您將學(xué)習(xí)更多關(guān)于如何使用WebDriver向前和向后導(dǎo)航,例如在你的瀏覽器的歷史,以及如何測試web站點使用幀和窗戶。我們還提供一個更詳細(xì)的討論和示例。

Selenium-WebDriver API Commands and Operations

Fetching a Page

The first thing you’re likely to want to do with WebDriver is navigate to a page. The normal way to do this is by calling “get”:

你可能想要做的第一件事和WebDriver導(dǎo)航到一個頁面。正常的方法是通過調(diào)用“get”:

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

Dependent on several factors, including the OS/Browser combination, WebDriver may or may not wait for the page to load. In some circumstances, WebDriver may return control before the page has finished, or even started, loading. To ensure robustness, you need to wait for the element(s) to exist in the page using Explicit and Implicit Waits.

取決于幾個因素,包括操作系統(tǒng)/瀏覽器組合,WebDriver可能會或可能不會等待頁面加載。在某些情況下,WebDriver可能返回控制頁面完成之前,甚至開始裝載。為了確保加載速度,您需要等待頁面中的元素(s)存在使用顯式和隱式等待。

Locating UI Elements (WebElements)

定位用戶界面元素(WebElements)

Locating elements in WebDriver can be done on the WebDriver instance itself or on a WebElement. Each of the language bindings expose a “Find Element” and “Find Elements” method. The first returns a WebElement object otherwise it throws an exception. The latter returns a list of WebElements, it can return an empty list if no DOM elements match the query.

WebDriver定位元素可以在完成本身或WebElement WebDriver實例。每種語言綁定公開“Find Element”和“Find Elements”方法。第一個返回一個WebElement對象否則它將拋出一個異常。后者WebElements返回一個列表,它能返回一個空列表如果沒有DOM元素匹配查詢。

The “Find” methods take a locator or query object called “By”. “By” strategies are listed below.

“Find”的方法來定位器或查詢對象稱為“By”。下面列出了“By”策略。

By ID

This is the most efficient and preferred way to locate an element. Common pitfalls that UI developers make is having non-unique id’s on a page or auto-generating the id, both should be avoided. A class on an html element is more appropriate than an auto-generated id.

這是最有效的和首選方法來定位一個元素。常見的陷阱,UI開發(fā)人員在一個頁面上有非唯一id或自動生成的id,都應(yīng)該避免.一個類一個html元素上比一個自動生成的id更合適。

Example of how to find an element that looks like this:

如何找到一個元素的例子是這樣的:

<div id="coolestWidgetEvah">...</div>
WebElement element = driver.findElement(By.id("coolestWidgetEvah"));
By Class Name

“Class” in this case refers to the attribute on the DOM element. Often in practical use there are many DOM elements with the same class name, thus finding multiple elements becomes the more practical option over finding the first element.

“類”在這種情況下是指DOM元素上的屬性.通常在實際使用DOM元素有很多相同的類名,從而發(fā)現(xiàn)多個元素變得更實用的選擇在找到第一個元素。

Example of how to find an element that looks like this:

<div class="cheese"><span>Cheddar</span></div><div class="cheese"><span>Gouda</span></div>
List<WebElement> cheeses = driver.findElements(By.className("cheese"));
By Tag Name

The DOM Tag Name of the element.

DOM元素的標(biāo)記名稱。

Example of how to find an element that looks like this:

<iframe src="..."></iframe>
WebElement frame = driver.findElement(By.tagName("iframe"));
By Name

Find the input element with matching name attribute.找到匹配的名稱屬性的輸入元素。

Example of how to find an element that looks like this:

<input name="cheese" type="text"/>
WebElement cheese = driver.findElement(By.name("cheese"));
By Link Text

Find the link element with matching visible text.找到匹配的可見文本鏈接元素。

Example of how to find an element that looks like this:

<a >cheese</a>>
WebElement cheese = driver.findElement(By.linkText("cheese"));
By Partial Link Text

Find the link element with partial matching visible text.發(fā)現(xiàn)部分匹配可見文本鏈接元素。

Example of how to find an element that looks like this:

<a >search for cheese</a>>
WebElement cheese = driver.findElement(By.partialLinkText("cheese"));
By CSS

Like the name implies it is a locator strategy by css. Native browser support is used by default, so please refer to w3c css selectors for a list of generally available css selectors. If a browser does not have native support for css queries, then Sizzle is used. IE 6,7 and FF3.0 currently use Sizzle as the css query engine.

喜歡這個名字意味著它是一個由css定位策略。在默認(rèn)情況下使用本機(jī)瀏覽器支持,所以請參閱w3c css選擇器投入使用css選擇器的列表。如果瀏覽器不支持css的查詢,然后使用Sizzle。IE 6、7和FF3.0目前使用Sizzle作為css查詢引擎。

Beware that not all browsers were created equal, some css that might work in one version may not work in another.

注意,并不是所有的瀏覽器都是平等的,一些css,可能工作在一個版本可能不會在另一個工作。

Example of to find the cheese below:

<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"));

At a high level, WebDriver uses a browser’s native XPath capabilities wherever possible. On those browsers that don’t have native XPath support, we have provided our own implementation. This can lead to some unexpected behaviour unless you are aware of the differences in the various xpath engines.

在高級別上,WebDriver盡可能使用瀏覽器的原生XPath功能。在那些沒有原生XPath支持的瀏覽器,我們提供自己的實現(xiàn)。這可能導(dǎo)致一些意想不到的行為,除非你知道各種xpath引擎的差異。

This is a little abstract, so for the following piece of HTML:

<input type="text" name="example" />
<INPUT type="text" name="other" />
List<WebElement> inputs = driver.findElements(By.xpath("http://input"));

The following number of matches will be found

Sometimes HTML elements do not need attributes to be explicitly declared because they will default to known values. For example, the “input” tag does not require the “type” attribute because it defaults to “text”. The rule of thumb when using xpath in WebDriver is that you should not expect to be able to match against these implicit attributes.

有時HTML元素不需要顯式聲明屬性,因為他們將默認(rèn)為已知值。例如,“輸入”標(biāo)簽不需要“type”屬性,因為它默認(rèn)為“文本”.WebDriver使用xpath時的經(jīng)驗法則是,你不應(yīng)該期望能夠匹配這些隱式屬性。

Using JavaScript

You can execute arbitrary javascript to find an element and as long as you return a DOM Element, it will be automatically converted to a WebElement object.

你可以執(zhí)行任意javascript來找到一個元素,只要你返回一個DOM元素,它將自動轉(zhuǎn)換為WebElement對象。

Simple example on a page that has jQuery loaded:

jQuery加載的頁面上的簡單的例子:

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

Finding all the input elements to the every label on a page:

找到所有的輸入元素上的每個標(biāo)簽頁:

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

We’ve already seen how to enter text into a textarea or text field, but what about the other elements? You can “toggle” the state of checkboxes, and you can use “click” to set something like an OPTION tag selected. Dealing with SELECT tags isn’t too bad:

我們已經(jīng)看到如何在文本區(qū)域輸入文本或文本字段,但是其他元素呢?你可以“切換”復(fù)選框的狀態(tài),你可以使用“點擊”設(shè)置這樣一個選項標(biāo)簽選擇。處理選擇標(biāo)簽并不是太糟了:

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();
}

This will find the first “SELECT” element on the page, and cycle through each of its OPTIONs in turn, printing out their values, and selecting each in turn. As you will notice, this isn’t the most efficient way of dealing with SELECT elements. WebDriver’s support classes include one called “Select”, which provides useful methods for interacting with these.

這將會發(fā)現(xiàn)第一個頁面上的“選擇”元素,并通過它的每個周期選項,打印出它們的值,并選擇每個。你會注意到,這并不是最有效的方式處理選擇元素。WebDriver類包括一個稱為“選擇”的支持,這對與這些交互提供了有用的方法。

Select select = new Select(driver.findElement(By.tagName("select")));
select.deselectAll();
select.selectByVisibleText("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:

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:

element.submit();

Moving Between Windows and Frames

窗口和框架之間的移動

Some web applications have many frames or multiple windows. WebDriver supports moving between named windows using the “switchTo” method:

一些web應(yīng)用程序有很多幀或多個窗口。WebDriver支持移動名為windows之間使用“switchTo”的方法:

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:

所有調(diào)用驅(qū)動程序現(xiàn)在將被視為被定向到特定的窗口。但是你怎么知道窗口的名字嗎?看一下打開它的javascript或鏈接:

<a href="somewhere.html" target="windowName">Click here to open a new window</a>

Alternatively, you can pass a “window handle” to the “switchTo().window()” method. Knowing this, it’s possible to iterate over every open window like so:

另外,您可以通過“窗口句柄”到“switchTo().window()方法。知道了這一點,可以遍歷所有打開的窗口如下所示:

for (String handle : driver.getWindowHandles()) {
    driver.switchTo().window(handle);
}

You can also switch from frame to frame (or into iframes):

您還可以切換從幀到幀(或iframes):

driver.switchTo().frame("frameName");

Popup Dialogs

彈出對話框

Starting with Selenium 2.0 beta 1, there is built in support for handling popup dialog boxes. After you’ve triggered an action that opens a popup, you can access the alert with the following:

從Selenium2.0 beta 1,內(nèi)建支持處理彈出對話框。觸發(fā)一個動作之后,打開一個彈出,您可以訪問以下警告:

Alert alert = driver.switchTo().alert();

This will return the currently open alert object. With this object you can now accept, dismiss, read its contents or even type into a prompt. This interface works equally well on alerts, confirms, and prompts. Refer to the JavaDocs or RubyDocs for more information.

這將返回當(dāng)前打開警報對象。這個對象現(xiàn)在可以接受,解雇,閱讀其內(nèi)容,甚至類型到一個提示。這個接口同樣適用于警報、確認(rèn)和提示。參考JavaDocs或RubyDocs獲得更多信息。

Navigation: History and Location

導(dǎo)航:歷史和位置

Earlier, we covered navigating to a page using the “get” command ( driver.get("http://www.example.com")) As you’ve seen, WebDriver has a number of smaller, task-focused interfaces, and navigation is a useful task. Because loading a page is such a fundamental requirement, the method to do this lives on the main WebDriver interface, but it’s simply a synonym to:

早些時候,我們覆蓋導(dǎo)航到一個頁面使用“get”命令(driver.get(“http://www.example.com”)如您所見,WebDriver有許多小,以任務(wù)為中心的界面,和導(dǎo)航是一個有用的任務(wù)。因為加載一個頁面是一個基本的要求,

這個方法做這個生活在主WebDriver接口,但它只是一個同義詞:

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

To reiterate: “navigate().to()” and “get()” do exactly the same thing. One’s just a lot easier to type than the other!

重申:navigate().to()” and “get()”做的是相同的事情,只是另一個更容易一點。

The “navigate” interface also exposes the ability to move backwards and forwards in your browser’s history:

“導(dǎo)航”界面也暴露前后移動的能力在你的瀏覽器的歷史:

driver.navigate().forward();
driver.navigate().back();

Please be aware that this functionality depends entirely on the underlying browser. It’s just possible that something unexpected may happen when you call these methods if you’re used to the behaviour of one browser over another.

請注意,此功能完全取決于底層的瀏覽器。只是可能會發(fā)生一些意想不到的事當(dāng)你調(diào)用這些方法如果你使用一個瀏覽器的行為。

Cookies

Before we leave these next steps, you may be interested in understanding how to use cookies. First of all, you need to be on the domain that the cookie will be valid for. If you are trying to preset cookies before you start interacting with a site and your homepage is large / takes a while to load an alternative is to find a smaller page on the site, typically the 404 page is small (http://example.com/some404page)

在我們離開這些步驟之前,你可能有興趣了解如何使用cookie。首先,你需要在域的Cookie的有效期,如果你想預(yù)定cookie在你開始與網(wǎng)站交互和你的主頁是大/需要一段時間來加載另一種方法是在網(wǎng)站上找到一個小頁面,通常404頁的小

// 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();

Changing the User Agent

修改用戶代理 

This is easy with the Firefox Driver:

FirefoxProfile profile = new FirefoxProfile();
profile.addAdditionalPreference("general.useragent.override", "some UA string");
WebDriver driver = new FirefoxDriver(profile);

Drag And Drop

拖拽

Here’s an example of using the Actions class to perform a drag and drop. Native events are required to be enabled.

這里有一個例子使用行為的類進(jìn)行拖拽。本地事件需要啟用。

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

(new Actions(driver)).dragAndDrop(element, target).perform();

Driver Specifics and Tradeoffs

Driver的細(xì)節(jié)和權(quán)衡

Selenium-WebDriver’s Drivers

WebDriver is the name of the key interface against which tests should be written, but there are several implementations. These include:

WebDriver是測試的關(guān)鍵接口的名字應(yīng)該寫,但有幾個實現(xiàn)。這些包括:

HtmlUnit Driver

This is currently the fastest and most lightweight implementation of WebDriver. As the name suggests, this is based on HtmlUnit. HtmlUnit is a java based implementation of a WebBrowser without a GUI. For any language binding (other than java) the Selenium Server is required to use this driver.

這是目前最快的和最輕量級WebDriver的實現(xiàn)。顧名思義,這是基于HtmlUnit。HtmlUnit是一個基于java的瀏覽器沒有GUI的實現(xiàn)。對任何語言綁定(除了java)Selenium服務(wù)器需要使用這個驅(qū)動程序。

Usage

使用

WebDriver driver = new HtmlUnitDriver();
Pros
  • Fastest implementation of WebDriver最快的實現(xiàn)WebDriver

  • A pure Java solution and so it is platform independent.純Java的解決方案,所以它是平臺獨立的。

  • Supports JavaScript支持JS

Cons
  • Emulates other browsers’ JavaScript behaviour (see below)模擬其他瀏覽器的JavaScript行為(見下文)

JavaScript in the HtmlUnit Driver

None of the popular browsers uses the JavaScript engine used by HtmlUnit (Rhino). If you test JavaScript using HtmlUnit the results may differ significantly from those browsers.

沒有一個流行的瀏覽器使用使用的JavaScript引擎HtmlUnit(犀牛)。如果您使用的測試JavaScript HtmlUnit結(jié)果從這些瀏覽器可能差別很大。

When we say “JavaScript” we actually mean “JavaScript and the DOM”. Although the DOM is defined by the W3C each browser has its own quirks and differences in their implementation of 

當(dāng)我們說“JavaScript”實際上意味著“JavaScript和DOM”。雖然由W3C DOM定義每個瀏覽器都有自己的怪癖和差異實施,DOM和JavaScript是如何進(jìn)行交互的。

the DOM and in how JavaScript interacts with it. HtmlUnit has an impressively complete implementation of the DOM and has good support for using JavaScript, but it is no different from any 

HtmlUnit有一個令人印象深刻的完整實現(xiàn)使用JavaScript DOM和具有良好的支持,但是它對其他瀏覽器沒有任何區(qū)別。

other browser: it has its own quirks and differences from both the W3C standard and the DOM implementations of the major browsers, despite its ability to mimic other browsers.

它有自己的怪癖和差異來自W3C標(biāo)準(zhǔn)和主流瀏覽器的DOM實現(xiàn),盡管其模仿其他瀏覽器的能力。

With WebDriver, we had to make a choice; do we enable HtmlUnit’s JavaScript capabilities and run the risk of teams running into problems that only manifest themselves there, or do we leave

WebDriver,我們不得不做出選擇;我們讓HtmlUnit的JavaScript功能和運行團(tuán)隊遇到的風(fēng)險問題,只有表現(xiàn),

 JavaScript disabled, knowing that there are more and more sites that rely on JavaScript? We took the conservative approach, and by default have disabled support when we use HtmlUnit. With 

知道越來越多的依賴于JavaScript的網(wǎng)站嗎?我們采取了保守的方法,當(dāng)我們使用HtmlUnit默認(rèn)情況下禁用支持

each release of both WebDriver and HtmlUnit, we reassess this decision: we hope to enable JavaScript by default on the HtmlUnit at some point.

WebDriver和HtmlUnit每個版本,我們評估這個決定:我們希望在HtmlUnit默認(rèn)啟用JavaScript。

Enabling JavaScript

If you can’t wait, enabling JavaScript support is very easy:

HtmlUnitDriver driver = new HtmlUnitDriver(true);

This will cause the HtmlUnit Driver to emulate Firefox 3.6’s JavaScript handling by default.

Firefox Driver

Controls the Firefox browser using a Firefox plugin. The Firefox Profile that is used is stripped down from what is installed on the machine to only include the Selenium WebDriver.xpi (plugin). A few settings are also changed by default (see the source to see which ones) Firefox Driver is capable of being run and is tested on Windows, Mac, Linux. Currently on versions 3.6, 10, latest - 1, latest

控制了Firefox瀏覽器使用Firefox插件。Firefox配置文件使用的是剝奪了從什么是安裝在機(jī)器上只包括硒WebDriver。xpi(插件)。一些默認(rèn)設(shè)置也改變了Firefox(見源代碼看到哪些)驅(qū)動程序可以運行和測試的在Windows,Mac,Linux。目前版本3.6,最新10 - 1,最新的。


向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI