Behave + Selenium(Python) 二
2016-02-03 15:44
531 查看
介绍feature, py文件和之间关系:
example01.feature文件包括5行: Feature行: 介绍这个feature用来干什么的; Scenario行:介绍这个scenario用来干什么的;Given: 一般数据的初始化在这里执行;When:执行操作;Then:验证结果。example01.py文件包括@given, @when, @then. 具体步骤实现在每一个对应的步骤里面实现。
接下来我们使用selenium来启动firefox浏览器,做一些页面上的操作和验证。 --可以使用exclipse或者Notepad++工具来写代码
一、新建文件夹example02,在文件夹里面新建example02.feature文件:
#../feature/example02/example02.feature
Feature:Search behave results in
baidu
Scenario: Search behave results in baidu
Given Access baidu
website
When Input behave characters
Then There are more than 1
results displaying
二、在example02文件夹里面新建steps文件夹,然后创建example02.py文件:
# This Python file uses the following encoding: utf-8
#../feature/example02/steps/example02.py
from selenium import webdriver
import time
import sys
@Given('Access baidu website')
def step_impl(context):
reload(sys)
sys.setdefaultencoding('utf-8') #设置python的编码方式为utf-8,它默认的是ACSII,
否则会报UnicodeDecodeError
context.driver = webdriver.Firefox()
context.driver.get("http://www.baidu.com")
@when('Input behave characters')
def step_impl(context):
context.ele_input = context.driver.find_element_by_xpath("//input[@id =
'kw']")
context.ele_input.send_keys("behave")
context.ele_btn = context.driver.find_element_by_xpath("//input[@id =
'su']")
context.ele_btn.click() time.sleep(10)
@Then('There are more than 1 results displaying')
def step_impl(context):
context.ele_results =
context.driver.find_element_by_css_selector("div.nums")
context.expected_results = '相关结果'
if context.expected_results in context.ele_results.text:
assert True
else:
assert False
三、打开cmd,cd到example02.feature所在的路径,然后输入behave, 结果运行正常:
![](https://images0.cnblogs.com/blog/670222/201411/232151359687750.jpg)
你会发现第一次我运行失败,原因是没有设置python的默认编码方式。
问题解决:
当使用中文字符的时候,会出现 SyntaxError:
Non-ASCII character '/xe6' 错误,这个时候,在python语句的第一行加上 # This Python file uses
the following encoding: utf-8 或者 #encoding: utf-8 即可以解决这个问题。以下为参考网址:
http://blog.csdn.net/mayflowers/article/details/1568852
https://www.python.org/dev/peps/pep-0263/
出现 UnicodeDecodeError: 'ascii' codec can't decode
byte 0xe7 in position 0: ordinal not in
range(128):加入以下代码进去,即可以解决问题。
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
相关文章推荐
- Behave + Selenium(Python)一:
- Python教程学习简记1--Python数据类型和变量 字符串和编码 list和tuple 条件判断 循环 dict和set
- 运用python 画圆
- python-------打印与字符串格式化
- python内置模块(二)
- webdriver 关于元素的常用操作 python版本
- python 注意事项(—)
- PEP8 Python编码规范
- Python 列表排序方法reverse、sort、sorted详解
- notepad++安装emmet和python script的方法
- Python进度条(tqdm)
- Python文件读写API
- 【卡尔曼滤波器-Python】The g-h filter white white noise(白噪声)
- python 笔记 寻找数列的规则
- python的输入参数
- [leetcode]@python 85. Maximal Rectangle
- [leetcode]@python 84. Largest Rectangle in Histogram
- Fatal error in launcher
- [leetcode]@python 83. Remove Duplicates from Sorted List
- python 笔记 break