`
cocoIT
  • 浏览: 51001 次
  • 性别: Icon_minigender_1
  • 来自: 福建
文章分类
社区版块
存档分类
最新评论

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”:

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 usingExplicit and Implicit Waits.

Locating UI Elements (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 returnsa WebElement object otherwise it throws an exception. The latter returns a list of WebElements, it canreturn an empty list if no DOM elements match the query.

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

By ID

This is the most efficient and preferred way to locate an element. Common pitfalls that UI developersmake is having non-unique id’s on a page or auto-generating the id, both should be avoided. A classon an html element is more appropriate than an auto-generated 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 aremany DOM elements with the same class name, thus finding multiple elements becomes the more practicaloption over finding the first element.

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.

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 href="http://www.google.com/search?q=cheese">cheese</a>>
WebElement cheese = driver.findElement(By.linkText("cheese"));

By Partial Link Text

Find the link element with partial matching visible text.

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

<a href="http://www.google.com/search?q=cheese">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 supportis used by default, so please refer to w3c css selectors <http://www.w3.org/TR/CSS/#selectors>for a list of generally available css selectors. If a browser does not havenative support for css queries, then Sizzle is used. IE 6,7 and FF3.0currently use Sizzle as the css query engine.

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

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

By XPATH

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

DriverTag and Attribute NameAttribute ValuesNative XPath Support
HtmlUnit Driver Lower-cased As they appear in the HTML Yes
Internet Explorer Driver Lower-cased As they appear in the HTML No
Firefox Driver Case insensitive As they appear in the HTML Yes

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

The following number of matches will be found

XPath expressionHtmlUnit DriverFirefox DriverInternet Explorer Driver
//input 1 (“example”) 2 2
//INPUT 0 2 0

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

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.

Simple example on a page that has jQuery loaded:

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

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

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 whatabout the other elements? You can “toggle” the state of checkboxes, and youcan use “click” to set something like an OPTION tag selected. Dealingwith SELECT tags isn’t too bad:

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 eachof 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 SELECTelements. WebDriver’s support classes include one called “Select”, whichprovides useful methods for interacting with these.

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 thenselect the OPTION with the displayed text of “Edam”.

Once you’ve finished filling out the form, you probably want to submit it. Oneway 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 DOMuntil it finds the enclosing form and then calls submit on that. If theelement 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 supportsmoving between named windows using the “switchTo” method:

driver.switchTo().window("windowName");

All calls to driver will now be interpreted as being directed to theparticular window. But how do you know the window’s name? Take a look at thejavascript or link that opened it:

<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:

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

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

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

It’s possible to access subframes by separating the path with a dot, and youcan specify the frame by its index too. That is:

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

would go to the frame named “child” of the first subframe of the frame called“frameName”. All frames are evaluated as if from *top*.

Popup Dialogs

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

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 equallywell on alerts, confirms, and prompts. Refer to the JavaDocsor RubyDocs for more information.

Navigation: History and Location

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

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!

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

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

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

Cookies

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

// 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.

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

(new Actions(driver)).dragAndDrop(element, target).perform();
分享到:
评论

相关推荐

    ruby+selenium-webdriver测试--第一个例子源代码

    Ruby+Selenium-Webdriver是一个强大的自动化测试工具组合,用于模拟真实用户在浏览器中与网页进行交互。Ruby是一种动态、面向对象的编程语言,而Selenium WebDriver是一个开源的自动化测试框架,支持多种浏览器和...

    selenium-webdriver-api文档

    这个文档,`selenium-API-2.12.chm`,是针对Selenium WebDriver 2.12版本的详细指南,对于理解和使用WebDriver API至关重要。 ### 1. WebDriver 概念 WebDriver 是一种接口,它提供了对浏览器的直接控制,支持多种...

    Selenium-Webdriver系列教程

    Selenium-Webdriver系列教程旨在引导读者理解和掌握Selenium 2.0,即WebDriver的核心概念、常用方法和高级功能。Selenium 1.x虽然已被弃用,但由于丰富的资源和历史积累,仍然被许多人广泛使用。然而,随着Selenium ...

    selenium-webdriver从入门到提高

    标题《Selenium-WebDriver从入门到提高》说明这是一本关于Selenium-WebDriver实用指南的书籍,旨在帮助读者从基础到进阶的各个层次上掌握Selenium-WebDriver的使用方法。Selenium-WebDriver作为一个自动化测试工具,...

    Selenium-WebDriverApi接口详解.py

    Selenium-WebDriverApi接口详解

    selenium-webdriver离线包.rar

    这个压缩包“selenium-webdriver离线包.rar”显然包含了在TypeScript或JavaScript环境中离线安装Selenium WebDriver所需的资源。 在TypeScript和JavaScript环境下使用Selenium WebDriver,首先需要理解这两者的基本...

    selenium-webdriver-2.24.0.gem

    注意selenium-webdriver只支持1.8.7以上的ruby版本; 使用gem安装selenium-webdriver;打开命令行,输入下列代码完成安装。注意,如果你的开发环境需要http proxy的话,请注意在gem命令中加入--http_proxy参数; ...

    selenium-webdriver-2.45.0.gem

    selenium-webdriver-2.45.0.gem

    ruby+selenium-webdriver测试源代码003

    在本资源中,我们关注的是使用Ruby和Selenium-Webdriver进行自动化测试的源代码,具体为"test003"。Ruby是一种流行的、动态的、面向对象的编程语言,而Selenium-Webdriver则是一个强大的工具,允许我们对浏览器进行...

    @typse-selenium-webdriver 智能提示.rar

    本教程将详细介绍如何离线安装 "@types/selenium-webdriver",以便在TypeScript项目中启用针对Selenium WebDriver的智能提示功能。 首先,让我们了解 "@types/selenium-webdriver" 的作用。这是一个npm(Node.js包...

    selenium-webdriver-2.40.0.gem

    selenium-webdriver-2.40.0.gem

    selenium-webdriver介绍PPT

    selenium-webdriver原创selenium-webdriver原创selenium-webdriver原创selenium-webdriver原创

    ruby+selenium-webdriver测试-测试用例源代码

    Ruby 和 Selenium-Webdriver 是一种强大的组合,用于自动化 Web 应用程序的测试。这篇博客主要探讨了如何利用这两种工具来编写测试用例,并提供了源代码示例。在这个压缩包中,我们有一个名为 "test002" 的文件,很...

    Selenium-Webdriver系列教程.docx

    Selenium-Webdriver 系列教程 本文主要介绍 Selenium 2.0 的一些基本知识、常用方法和高级扩展,所有代码和示例均由 Ruby 编写,主要是 ruby binding。首先,需要确保 Ruby 语言在开发环境上正确安装。 Selenium ...

    selenium-webdriver-2.5.0

    selenium-webdriver-2.5.0.gem

    ruby2.0.0+selenium-webdriver+watir-webdriver+rails离线备份

    ruby2.0.0+selenium-webdriver+watir-webdriver+rails离线备份,设置环境变量后可使用(未测试)

    ruby+selenium-webdriver测试--多个测试用例源代码

    在Ruby编程语言中,Selenium-Webdriver是一个强大的工具,用于进行自动化Web浏览器测试。它允许开发者编写脚本来模拟用户与网页的交互,从而验证应用的功能和行为。本篇文章将深入探讨如何使用Ruby和Selenium-...

    selenium-WebDriver的API文档

    **Selenium WebDriver API 文档详解** Selenium 是一个强大的开源自动化测试工具,广泛应用于Web应用程序的测试。它的WebDriver API 提供了一种编程接口,允许测试人员通过多种编程语言(如Java、Python、C#等)...

    selenium-webdriver-java api文档

    **Selenium WebDriver Java API 文档详解** Selenium WebDriver 是一个自动化测试工具,广泛用于Web应用程序的测试。它提供了一个编程接口(API),允许开发者用多种编程语言(包括Java)来控制浏览器并执行自动化...

    selenium-webdriver-4.8.6.gem

    selenium-webdriver-4.8.6.gem

Global site tag (gtag.js) - Google Analytics