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. hibernate对象关系映射的配置

    一对一主键关联单双向 <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-m ...

  2. Sqli-labs less 3

    Less-3 我们使用?id=' 注入代码后,我们得到像这样的一个错误: MySQL server version for the right syntax to use near "&qu ...

  3. 输入输出格式之Python版

    # 有多组输入数据,但没有具体的告诉你有多少组,只是让你对应每组输入,应该怎样输出. while True: try: a, b = map(int, raw_input().strip().spli ...

  4. java中ThreadLocal类的使用

    ThreadLocal是解决线程安全问题一个很好的思路,ThreadLocal类中有一个Map,用于存储每一个线程的变量副本,Map中元素的键为线程对象,而值对应线程的变量副本,由于Key值不可重复, ...

  5. [BZOJ3456]城市规划(生成函数+多项式求逆+多项式求ln)

    城市规划 时间限制:40s      空间限制:256MB 题目描述 刚刚解决完电力网络的问题, 阿狸又被领导的任务给难住了.  刚才说过, 阿狸的国家有n个城市, 现在国家需要在某些城市对之间建立一 ...

  6. hdu 3547 (polya定理 + 小高精)

    DIY CubeTime Limit: 2000/2000 MS (Java/Others)    Memory Limit: 65535/32768 K (Java/Others)Total Sub ...

  7. HDU 6052 To my boyfriend(悬线法)

    [题目链接] http://acm.hdu.edu.cn/showproblem.php?pid=6052 [题目大意] 给出一个数字矩阵,求子矩阵期望数字种数 [题解] 我们统计[x,y]为其所表示 ...

  8. Python的高级特性(切片,迭代,生成器,迭代器)

    掌握了python的数据类型,语句和函数,基本上就可以编出很多有用的程序了. 但是在python中,并不是代码越多越好,代码不是越复杂越好,而是越简单越好. 基于这个思想,就引申出python的一些高 ...

  9. Ubuntu 16.04安装RabbitMQ(单机版)

    说明: 1.如果是做RabbitMQ方面的开发时,建议先不要了解集群的安装和部署,先安装一个单机版之后,尽快的熟悉里面的功能和特性.毕竟单机版支持的QPS相当的高.同样,集群方式也没有想象中的多点复制 ...

  10. Matlab横坐标从特定值开始

    set(gca,'XTick',1:1:length(x)); set(gca,'XTickLabel',{'15','20','25','30','35','40','45','50','55',' ...