開始進入實際階段,拿百度來做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之類的函數.增加可讀性.