开始进入实际阶段,拿百度来做demo,先实现登录和搜索.
分析:登录是一个前置操作,需要经常用到的前置条件,所以作为固件函数放到conftest中,搜索功能单独写成一个函数
conftest.py
# coding:utf-8
"""
author:@zhouxuan
@note:fixture
"""
from selenium import webdriver
import pytest
from selenium.webdriver.support.wait import WebDriverWait
import time
from selenium.webdriver.remote.webdriver import By
@pytest.fixture(scope='module')
def login_baidu():
dr = webdriver.Chrome()
dr.get('http://www.baidu.com')
dr.maximize_window()
time.sleep(4)
dr.find_element(By.XPATH,"//div[@id='u1']//a[@name='tj_login']").click()
"判断默认展示的是扫码登录还是用户名登录"
try:
WebDriverWait(dr, 2).until(lambda x: x.find_element_by_xpath('//p[@title="用户名登录"][not(@style)]').is_displayed())
b=1
except:
b=2 #默认登录方式未扫码
if b==1:
dr.find_element("xpath",'//p[@title="用户名登录"]').click()
dr.find_element(By.NAME,"userName").send_keys('*********')
dr.find_element(By.NAME,"password").send_keys('*****')
dr.find_element(By.ID,"TANGRAM__PSP_10__submit").click()
print('one')
yield dr
time.sleep(5)
dr.quit()
test_baidu.py
# coding:utf-8
"""
author:@
"""
import pytest
from selenium.webdriver.remote.webdriver import By
from selenium.webdriver.common.keys import Keys
class Test_baidu():
def test_search(self,login_baidu):
dr=login_baidu
dr.find_element(By.ID,"kw").send_keys('aaa',Keys.ENTER)
if __name__ == '__main__':
pytest.main(['-s','test_baidu.py'])
执行脚本,正常完成.
============================= test session starts =============================
platform win32 -- Python 3.6.8, pytest-5.0.0, py-1.5.4, pluggy-0.13.1
rootdir: D:\django_project\p3_tongtool, inifile: pytest.ini
plugins: allure-pytest-2.8.6, html-2.0.1, metadata-1.8.0, rerunfailures-8.0
collected 1 item
test_baidu.py one
.
========================== 1 passed in 21.10 seconds ==========================
待优化问题:因为测试脚本中的dr是从login_baidu中的浏览器对象赋值而来,所以在没有执行的时候,编写脚本的时候,不能带出selenium相关的函数,较为不变,接下来就考虑如何去封装常用的写法,在执行脚本中,不去引用selenium中的find_element_by_xpath之类的函数.增加可读性.