selenium-Navigating

The first thing you’ll want to do with WebDriver is navigate to a link. The normal way to do this is by calling get method:

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

WebDriver will wait until the page has fully loaded (that is, the onload event has fired) before returning control to your test or script. It’s worth noting that if your page uses a lot of AJAX on load then WebDriver may not know when it has completely loaded. If you need to ensure such pages are fully loaded then you can use waits.

1.1. Interacting with the page

Just being able to go to places isn’t terribly useful. What we’d really like to do is to interact with the pages, or, more specifically, the HTML elements within a page. First of all, we need to find one. WebDriver offers a number of ways to find elements. For example, given an element defined as:

<input type="text" name="passwd" id="passwd-id" />

you could find it using any of:

element = driver.find_element_by_id("passwd-id")
element = driver.find_element_by_name("passwd")
element = driver.find_element_by_xpath("//input[@id=‘passwd-id‘]")

You can also look for a link by its text, but be careful! The text must be an exact match! You should also be careful when using XPATH in WebDriver. If there’s more than one element that matches the query, then only the first will be returned. If nothing can be found, a NoSuchElementException will be raised.

WebDriver has an “Object-based” API; we represent all types of elements using the same interface. This means that although you may see a lot of possible methods you could invoke when you hit your IDE’s auto-complete key combination, not all of them will make sense or be valid. Don’t worry! WebDriver will attempt to do the Right Thing, and if you call a method that makes no sense (“setSelected()” on a “meta” tag, for example) an exception will be raised.

So, you’ve got an element. What can you do with it? First of all, you may want to enter some text into a text field:

element.send_keys("some text")

You can simulate pressing the arrow keys by using the “Keys” class:

element.send_keys(" and some", Keys.ARROW_DOWN)

It is possible to call send_keys on any element, which makes it possible to test keyboard shortcuts such as those used on GMail. A side-effect of this is that typing something into a text field won’t automatically clear it. Instead, what you type will be appended to what’s already there. You can easily clear the contents of a text field or textarea with clear method:

element.clear()

1.2. 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 drop down, and you can use “setSelected” to set something like an OPTION tag selected. Dealing with SELECT tags isn’t too bad:

element = driver.find_element_by_xpath("//select[@name=‘name‘]")
all_options = element.find_elements_by_tag_name("option")
for option in all_options:
    print("Value is: %s" % option.get_attribute("value"))
    option.click()

This will find the first “SELECT” element on the page, and cycle through each of it’s OPTIONs in turn, printing out their values, and selecting each in turn.

As you can see, 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:

from selenium.webdriver.support.ui import Select
select = Select(driver.find_element_by_name(‘name‘))
select.select_by_index(index)
select.select_by_visible_text("text")
select.select_by_value(value)

WebDriver also provides features for deselecting all the selected options:

select = Select(driver.find_element_by_id(‘id‘))
select.deselect_all()

This will deselect all OPTIONs from the first SELECT on the page.

Suppose in a test, we need the list of all default selected options, Select class provides a property method that returns a list:

select = Select(driver.find_element_by_xpath("xpath"))
all_selected_options = select.all_selected_options

To get all available options:

options = select.options

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:

# Assume the button has the ID "submit" :)
driver.find_element_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 raised:

element.submit()

1.3. Drag and drop

You can use drag and drop, either moving an element by a certain amount, or on to another element:

element = driver.find_element_by_name("source")
target = driver.find_element_by_name("target")

from selenium.webdriver import ActionChains
action_chains = ActionChains(driver)
action_chains.drag_and_drop(element, target).perform()

1.4. Moving between windows and frames

It’s rare for a modern web application not to have any frames or to be constrained to a single window. WebDriver supports moving between named windows using the “switch_to_window” method:

driver.switch_to_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:

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

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

for handle in driver.window_handles:
    driver.switch_to_window(handle)

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

driver.switch_to_frame("frameName")

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

driver.switch_to_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*.

Once we are done with working on frames, we will have to come back to the parent frame which can be done using:

driver.switch_to_default_content()

1.5. Popup dialogs

Selenium WebDriver has built-in support for handling popup dialog boxes. After you’ve triggerd action that would open a popup, you can access the alert with the following:

alert = driver.switch_to_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, prompts. Refer to the API documentation for more information.

1.6. 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 a number of smaller, task-focused interfaces, and navigation is a useful task. To navigate to a page, you can use get method:

driver.get("http://www.example.com")

To move backwards and forwards in your browser’s history:

driver.forward()
driver.back()

Please be aware that this functionality depends entirely on the underlying driver. 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.

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

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

# Now set the cookie. This one‘s valid for the entire domain
cookie = {‘name’ : ‘foo’, ‘value’ : ‘bar’}
driver.add_cookie(cookie)

# And now output all the available cookies for the current URL
driver.get_cookies()
时间: 2024-08-03 05:19:42

selenium-Navigating的相关文章

&lt;译&gt;Selenium Python Bindings 3 - Navigating

当你想要通过webdriver导航到一个链接,正常的方式点是通过调用get方法: driver.get("http://www.google.com") Interacting with the page在页面中的HTML元素.如果我们需要找到定位一个.那么webdriver提供了许多方法来寻找元素.例如给了一个HTML的标签: <input type="text" name="passwd" id="passwd-id"

selenium docs

Note to the Reader - Docs Being Revised for Selenium 2.0! Introduction Test Automation for Web Applications To Automate or Not to Automate? Introducing Selenium Brief History of The Selenium Project Selenium’s Tool Suite Choosing Your Selenium Tool S

浅析selenium的PageFactory模式

前面的文章介绍了selenium的PO模式,见文章:http://www.cnblogs.com/qiaoyeye/p/5220827.html.下面介绍一下PageFactory模式. 1.首先介绍FindBy类: For example, these two annotations point to the same element: @FindBy(id = "foobar") WebElement foobar; @FindBy(how = How.ID, using = &q

关于在selenium 中 webdriver 截图操作

package prictce; import java.io.File; import java.io.IOException; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.openqa.selenium.OutputType; import org.openqa.selenium.TakesScreenshot; import org.openqa.selenium.We

python selenium 处理时间日期控件(十五)

测试过程中经常遇到时间控件,需要我们来选择日期,一般处理时间控件通过层级定位来操作或者通过调用js来实现. 1.首先我们看一下如何通过层级定位来操作时间控件. 通过示例图可以看到,日期控件是无法输入日期,点击后弹出日期列表供我们选择日期,自己找了一个日期控制演示一下,通过两次定位,选择了日期 #-*- coding:utf-8 -*- import time from selenium import webdriver driver = webdriver.Chrome() driver.get

selenium+python在mac环境上的搭建

前言 mac自带了python2.7的环境,所以在mac上安装selenium环境是非常简单的,输入2个指令就能安装好 需要安装的软件: 1.pip 2.selenium2.53.6 3.Firefox44.dmg 4.Pycharm (环境搭配selenium2+Firefox46及以下版本兼容,selenium3+Firefox47+geckodriver) 一.selenium安装 1.mac自带了python2.7,python里面又自带了easy_install工具,所以安装pip用e

Selenium+Java+Eclipse 自动化测试环境搭建

一.下载Java windows java下载链接 https://www.java.com/zh_CN/download/win10.jsp 二.安装Java 安装好后检查一下需不需要配置环境变量,现在java 8已经不用配置环境变量了,直接在命令行输入:java -version 三.下载和安装Eclipse windows Eclipse下载链接 https://www.eclipse.org/downloads/ 你也可以下载绿色版 四.下载selenium,然后解压 selenium

selenium学习笔记(1) 搭建环境

1. 用Eclipse创建maven工程,在pom.xml中添加依赖 1 <!-- https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-java --> 2 <dependency> 3 <groupId>org.seleniumhq.selenium</groupId> 4 <artifactId>selenium-java</artifactId>

python selenium webderiver 遇到的问题

from selenium import webdriver driver = webdriver.Firefox(executable_path = "C:/Insert/Firefox/geckodriver.exe")driver.get("http://www.baidu.com")driver.maximize_window() driver.find_element_by_id("kw").send_keys("seleni

Selenium+Python的环境配置

因为项目的原因,最近较多的使用了UFT来进行自动化测试工作,半年没有使用Selenium了,于是在自己的电脑上重新配置了基于python3.x的selenium环境,配置过程大致如下: 1. Selenium安装 Selenium在python下的环境配置相对简单,只需在python中安装selenium的包即可. 2. Webdriver安装 但对于针对不同浏览器的webdriver还需单独安装. 之前在使用python2时,并没有对firefox浏览器安装单独的driver,但这次发现对于f