python + selenium 自动化测试

来源:互联网 发布:hm怎么没有淘宝旗舰店 编辑:程序博客网 时间:2024/04/27 20:55
1、下载并安装python(http://www.python.org/getit/,selenium暂时不支持python3,这里使用2.7.3版本)。


2、下载并安装setuptools(http://pypi.python.org/pypi/setuptools,这里使用setuptools-0.6c11.win32-py2.7版本)。


3、下载pip(http://pypi.python.org/pypi/pip,这里使用pip-1.2.1.tar.gz版本),解压缩之后,
使用cmd命令:python setup.py install(如果python命令使用不成功,请配置下python的环境变量),打开cmd命令,进入python的scripts目录(比如c:\python27\scripts),输入easy_install pip。


4、安装selenium(http://pypi.python.org/pypi/selenium),联网的话直接使用pip安装,
命令进入python的scripts目录,执行:pip install -U selenium;没联网的话,解压缩selenium-2.28.0.tar.gz. 把selenium整个文件夹放入Python27\Lib\site-packages目录下。


5、下载并安装java(http://www.java.com/zh_CN/)。


6、下载selenium的服务端(http://selenium.googlecode.com/files/selenium-server-standalone-2.28.0.jar),
在selenium-server-standalone-2.28.0.jar目录下使用命令java -jar selenium-server-standalone-2.28.0.jar启动(如果打不开,查看是否端口被占用:netstat -aon|findstr 4444)。


7、打开python的idle,运行如下脚本,看运行是否成功。
# coding=gbk
from selenium import webdriver

browser = webdriver.Firefox() # 打开火狐浏览器
browser.get("http://www.baidu.com") # 登录百度首页


8、要想支持IE,下载IEDriverServer(http://code.google.com/p/selenium/downloads/detail?name=IEDriverServer_Win32_2.28.0.zip),解压缩之后,将exe程序放在安装python的根目录下。


9、运行过程中如果出现WebDriverException: Message:
u'Unexpected error launching Internet Explorer. Protected Mode settings are
 not the same for all zones. Enable Protected Mode must be set to the same value (enabled or disabled) for all zones.' 这个错误,更改IE的internet选项->安全,
 将Internet/本地Internet/受信任的站定/受限制的站点中的启用保护模式全部去掉勾,或者全部勾上。下面是一个IE的例子,打开百度,自动搜索selenium。

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

driver = webdriver.Ie()
driver.get("http://www.baidu.com")
elem = driver.find_element_by_name("wd")
elem.send_keys("selenium")
elem.send_keys(Keys.RETURN)
原创粉丝点击