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. HRBUST 1217 统计单词个数

    $dp$. 设$dp[i][j]$为到$i$位置,切成了$j$段的最大收益,然后枚举一下$f$,$dp[i][j]=max(dp[f][j-1]+v[f+1][i])$.一段区间的价值可以用区间$dp ...

  2. ansible学习-playbook的YAML语法

    [一篇非常好的ansible参考博文] 初识Ansible http://liumissyou.blog.51cto.com/4828343/1616462 --------------------- ...

  3. 【hihoCoder 第133周】【hihoCoder 1467】2-SAT·hihoCoder音乐节

    http://hihocoder.com/problemset/problem/1467 2-sat模板...详细的题解请看题目里的提示. tarjan模板打错again致命伤qwq #include ...

  4. 洛谷P1113 杂务

    题目描述 John的农场在给奶牛挤奶前有很多杂务要完成,每一项杂务都需要一定的时间来完成它.比如:他们要将奶牛集合起来,将他们赶进牛棚,为奶牛清洗乳房以及一些其它工作.尽早将所有杂务完成是必要的,因为 ...

  5. [NOIP2016]天天爱跑步(树上差分+线段树合并)

    将每个人跑步的路径拆分成x->lca,lca->y两条路径分别考虑: 对于在点i的观察点,这个人(s->t)能被观察到的充要条件为: 1.直向上的路径:w[i]=dep[s]-dep ...

  6. AGC 012 D - Colorful Balls

    题面在这里! 为什么atcoder都是神仙题啊qwq 首先发现如果要让 x,y 互换位置的话,要么通过他们直接换 (也就是x和y满足两种操作之一),要么间接换,通过一些其他的元素形如 x可以和 a[1 ...

  7. 【树形dp】Apple Tree

    [poj2486]Apple Tree Time Limit: 1000MS   Memory Limit: 65536K Total Submissions: 10800   Accepted: 3 ...

  8. 【高斯消元】CDOJ1785 曜酱的线性代数课堂(三)

    高斯消元求行列式板子. #include<cstdio> #include<cmath> #include<algorithm> #include<cstri ...

  9. 【分块】【LCT】bzoj2002 [Hnoi2010]Bounce 弹飞绵羊

    分块,每个点统计还有几步弹出该块,以及它弹出块后的下一个节点是哪个点. 注意:update某个点的时候,会可能对当前块内 该点及以前的点 产生影响,所以对这部分点进行更新. #include<c ...

  10. android系统各种音量的获取与设置

    获取系统音量 通过程序获取android系统手机的铃声和音量.同样,设置铃声和音量的方法也很简单! 设置音量的方法也很简单,AudioManager提供了方法: publicvoidsetStream ...