1.1. Simple Usage

If you have installed Selenium Python bindings, you can start using it from Python like this.

from selenium import webdriver
from selenium.webdriver.common.keys import Keys driver = webdriver.Firefox()
driver.get("http://www.python.org")
assert "Python" in driver.title
elem = driver.find_element_by_name("q")
elem.send_keys("pycon")
elem.send_keys(Keys.RETURN)
assert "No results found." not in driver.page_source
driver.close()

The above script can be saved into a file (eg:- python_org_search.py), then it can be run like this:

python python_org_search.py

The python which you are running should have the selenium module installed.

1.2. Walk through of the example

The selenium.webdriver module provides all the WebDriver implementations. Currently supported WebDriver implementations are Firefox, Chrome, Ie and Remote. The Keys class provide keys in the keyboard like RETURN, F1, ALT etc.

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

Next, the instance of Firefox WebDriver is created.

driver = webdriver.Firefox()

The driver.get method will navigate to a page given by the URL. 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.:

driver.get("http://www.python.org")

The next line is an assertion to confirm that title has “Python” word in it:

assert "Python" in driver.title

WebDriver offers a number of ways to find elements using one of the find_element_by_* methods. For example, the input text element can be located by its name attribute using find_element_by_namemethod. Detailed explanation of finding elements is available in the Locating Elements chapter:

elem = driver.find_element_by_name("q")

Next we are sending keys, this is similar to entering keys using your keyboard. Special keys can be send using Keys class imported from selenium.webdriver.common.keys:

elem.send_keys("pycon")
elem.send_keys(Keys.RETURN)

After submission of the page, you should get the result if there is any. To ensure that some results are found, make an assertion:

assert "No results found." not in driver.page_source

Finally, the browser window is closed. You can also call quit method instead of close. The quit will exit entire browser whereas close` will close one tab, but if just one tab was open, by default most browser will exit entirely.:

driver.close()

1.3. Using Selenium to write tests

Selenium is mostly used for writing test cases. The selenium package itself doesn’t provide a testing tool/framework. You can write test cases using Python’s unittest module. The other options for a tool/framework are py.test and nose.

In this chapter, we use unittest as the framework of choice. Here is the modified example which uses unittest module. This is a test for python.org search functionality:

import unittest
from selenium import webdriver
from selenium.webdriver.common.keys import Keys class PythonOrgSearch(unittest.TestCase): def setUp(self):
self.driver = webdriver.Firefox() def test_search_in_python_org(self):
driver = self.driver
driver.get("http://www.python.org")
self.assertIn("Python", driver.title)
elem = driver.find_element_by_name("q")
elem.send_keys("pycon")
elem.send_keys(Keys.RETURN)
assert "No results found." not in driver.page_source def tearDown(self):
self.driver.close() if __name__ == "__main__":
unittest.main()

You can run the above test case from a shell like this:

python test_python_org_search.py
.
----------------------------------------------------------------------
Ran 1 test in 15.566s OK

The above result shows that the test has been successfully completed.

1.4. Walk through of the example

Initially, all the basic modules required are imported. The unittest module is a built-in Python based on Java’s JUnit. This module provides the framework for organizing the test cases. The selenium.webdriver module provides all the WebDriver implementations. Currently supported WebDriver implementations are Firefox, Chrome, Ie and Remote. The Keys class provide keys in the keyboard like RETURN, F1, ALT etc.

import unittest
from selenium import webdriver
from selenium.webdriver.common.keys import Keys

The test case class is inherited from unittest.TestCase. Inheriting from TestCase class is the way to tell unittest module that this is a test case:

class PythonOrgSearch(unittest.TestCase):

The setUp is part of initialization, this method will get called before every test function which you are going to write in this test case class. Here you are creating the instance of Firefox WebDriver.

def setUp(self):
self.driver = webdriver.Firefox()

This is the test case method. The test case method should always start with characters test. The first line inside this method create a local reference to the driver object created in setUp method.

def test_search_in_python_org(self):
driver = self.driver

The driver.get method will navigate to a page given by the URL. 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.:

driver.get("http://www.python.org")

The next line is an assertion to confirm that title has “Python” word in it:

self.assertIn("Python", driver.title)

WebDriver offers a number of ways to find elements using one of the find_element_by_* methods. For example, the input text element can be located by its name attribute using find_element_by_namemethod. Detailed explanation of finding elements is available in the Locating Elements chapter:

elem = driver.find_element_by_name("q")

Next we are sending keys, this is similar to entering keys using your keyboard. Special keys can be send using Keys class imported from selenium.webdriver.common.keys:

elem.send_keys("pycon")
elem.send_keys(Keys.RETURN)

After submission of the page, you should get result as per search if there is any. To ensure that some results are found, make an assertion:

assert "No results found." not in driver.page_source

The tearDown method will get called after every test method. This is a place to do all cleanup actions. In the current method, the browser window is closed. You can also call quit method instead of close. The quit will exit the entire browser, whereas close will close a tab, but if it is the only tab opened, by default most browser will exit entirely.:

def tearDown(self):
self.driver.close()

Final lines are some boiler plate code to run the test suite:

if __name__ == "__main__":
unittest.main()

1.5. Using Selenium with remote WebDriver

To use the remote WebDriver, you should have Selenium server running. To run the server, use this command:

java -jar selenium-server-standalone-2.x.x.jar

While running the Selenium server, you could see a message looking like this:

15:43:07.541 INFO - RemoteWebDriver instances should connect to: http://127.0.0.1:4444/wd/hub

The above line says that you can use this URL for connecting to remote WebDriver. Here are some examples:

from selenium.webdriver.common.desired_capabilities import DesiredCapabilities

driver = webdriver.Remote(
command_executor='http://127.0.0.1:4444/wd/hub',
desired_capabilities=DesiredCapabilities.CHROME) driver = webdriver.Remote(
command_executor='http://127.0.0.1:4444/wd/hub',
desired_capabilities=DesiredCapabilities.OPERA) driver = webdriver.Remote(
command_executor='http://127.0.0.1:4444/wd/hub',
desired_capabilities=DesiredCapabilities.HTMLUNITWITHJS)

The desired capabilities is a dictionary, so instead of using the default dictionaries, you can specify the values explicitly:

driver = webdriver.Remote(
command_executor='http://127.0.0.1:4444/wd/hub',
desired_capabilities={'browserName': 'htmlunit',
'version': '2',
'javascriptEnabled': True})

selenium-Getting Started的更多相关文章

  1. Python爬虫小白入门(四)PhatomJS+Selenium第一篇

    一.前言 在上一篇博文中,我们的爬虫面临着一个问题,在爬取Unsplash网站的时候,由于网站是下拉刷新,并没有分页.所以不能够通过页码获取页面的url来分别发送网络请求.我也尝试了其他方式,比如下拉 ...

  2. Selenium的PO模式(Page Object Model)[python版]

     Page Object Model 简称POM  普通的测试用例代码: .... #测试用例 def test_login_mail(self): driver = self.driver driv ...

  3. selenium元素定位篇

    Selenium webdriver是完全模拟用户在对浏览器进行操作,所有用户都是在页面进行的单击.双击.输入.滚动等操作,而webdriver也是一样,所以需要我们指定元素让webdriver进行单 ...

  4. selenium自动化基础知识

    什么是自动化测试? 自动化测试分为:功能自动化和性能自动化 功能自动化即使用计算机通过编码的方式来替代手工测试,完成一些重复性比较高的测试,解放测试人员的测试压力.同时,如果系统有不份模块更改后,只要 ...

  5. 幼儿园的 selenium

    from selenium import webdriver     *固定开头     b=webdriver.Firefox()              *打开火狐浏览器    browser. ...

  6. 使用selenium编写脚本常见问题(一)

    前提:我用selenium IDE录制脚本,我用java写的脚本,如果大家想看的清楚明白推荐java/Junit4/Webdriver 我用的是java/TestNG/remote control 1 ...

  7. 关于selenium RC的脚本开发

    第一.需要录制脚本,找个我也不说了.就是在firefox下下载一个selenium-IDE并且安装. 第二.在工具里找到selenium-IDE点击运行. 第三.默认是红色按钮点击状态的,接下来随便你 ...

  8. 基于python的selenium自动化测试环境安装

    1. Python2安装 官方网站:https://www.python.org/downloads/ (python3或新版本已经默认集成了pip包和path,安装的时候打勾就行,可以直接跳过下面第 ...

  9. Selenium+python 配置

    1. 安装python, www.python.org. 下载最新的python,应该是32位的.注意配置环境变量. 2. 安装PIP(pip是一个以Python计算机程序语言写成的软件包管理系统). ...

  10. selenium 使用action进行鼠标,键盘操作

    <!--test.html--> <html> <head> <title>Set Timeout</title> <script&g ...

随机推荐

  1. 阿里云轻量级学生机搭建FTP最新教程

    碰了几次壁,我整理一下分析自己在阿里云上成功安装FTP的教程. 1.使用root用户进入云服务器. 2.rpm  -qa|grep vsftpd 查看是否安装了ftp,一般阿里云服务器你以前没安装过, ...

  2. SCU 4444 Travel (补图最短路)

    Travel The country frog lives in has \(n\) towns which are conveniently numbered by \(1, 2, \dots, n ...

  3. 文件包含漏洞检测工具fimap

    文件包含漏洞检测工具fimap   在Web应用中,文件包含漏洞(FI)是常见的漏洞.根据包含的文件不同,它分为本地文件包含漏洞(LFI)和远程文件包含漏洞(RFL).利用该漏洞,安全人员可以获取服务 ...

  4. 【BZOJ 1150】 1150: [CTSC2007]数据备份Backup (贪心+优先队列+双向链表)

    1150: [CTSC2007]数据备份Backup Description 你在一家 IT 公司为大型写字楼或办公楼(offices)的计算机数据做备份.然而数据备份的工作是枯燥乏味 的,因此你想设 ...

  5. CodeForces - 1000D Yet Another Problem On a Subsequence

    题面在这里! 好智障的一个dp啊,一段开头的数字相当于下面要跟多少个数,直接滚动数组dp就行了... #include<bits/stdc++.h> #define ll long lon ...

  6. 【容斥原理】Codeforces Round #428 (Div. 2) D. Winter is here

    给你一个序列,让你对于所有gcd不为1的子序列,计算它们的gcd*其元素个数之和. 设sum(i)为i的倍数的数的个数,可以通过容斥算出来. 具体看这个吧:http://blog.csdn.net/j ...

  7. 【OpenJudge9275】【Usaco2009 Feb】【递推】Bullcow

    Bullcow 总时间限制: 12000ms 单个测试点时间限制: 1000ms 内存限制: 131072kB [描述] 一年一度的展会要来临了,农民约翰想要把N(1 <= N <= 10 ...

  8. [转]115个Java面试题和答案——终极列表(上)

    本文我们将要讨论Java面试中的各种不同类型的面试题,它们可以让雇主测试应聘者的Java和通用的面向对象编程的能力.下面的章节分为上下两篇,第一篇将要讨论面向对象编程和它的特点,关于Java和它的功能 ...

  9. Manthan, Codefest 16 B. A Trivial Problem 二分 数学

    B. A Trivial Problem 题目连接: http://www.codeforces.com/contest/633/problem/B Description Mr. Santa ask ...

  10. 使用phpExcel实现Excel数据的导入导出(完全步骤)

    使用phpExcel实现Excel数据的导入导出(完全步骤)   很多文章都有提到关于使用phpExcel实现Excel数据的导入导出,大部分文章都差不多,或者就是转载的,都会出现一些问题,下面是本人 ...