我們的測試用例是:打開百度首頁,搜索Selenium,然後檢查搜索列表,有沒有Selenium這個官網鏈接選項。
在寫自動化腳本之前,需要明確手動腳本的步驟,然後去拆分到具體沒一個步驟做什麼,考慮好了之後,纔開始動手去寫腳本。我把這個測試場景分拆如下步驟:
1) 啓動後瀏覽器,這裏我們用Chrome
2) 打開百度首頁,https://www.baidu.com
3) 定位搜索輸入框,記錄下輸入框元素的xpath表達式://*[@id='kw']
4) 定位搜索提交按鈕(百度一下這個按鈕),獲取xpath表達式://*[@id='su']
5) 在搜索輸入框輸入“Selenium”,點擊百度一下這個按鈕。
6) 在搜索結果列表去判斷是否存在Selenium官網這個鏈接。
7) 退出瀏覽器,結束測試。
1) 桌面新建一個記事本,命名並保存爲First.py
2) 輸入如下代碼片段到First.py,保存
3) 打開cmd窗口,切換到桌面路徑下,然後通過python First.py 來執行腳本。
import time
from selenium import webdriver
driver = webdriver.Chrome()
driver.maximize_window() # 最大化瀏覽器
driver.implicitly_wait(8) # 設置隱式時間等待
driver.get("https://www.baidu.com")
#input = driver.find_element_by_id('kw')
#input.send_keys('Selenium')
driver.find_element_by_id('kw').send_keys('Selenium') # 定位輸入框,輸入Selenium
#submit = driver.find_element_by_id('su')
#submit.click()
driver.find_element_by_id('su').click()#定位按鈕'百度一下',點擊按鈕
time.sleep(3)
# 通過selenium方法is_displayed() 來判斷我們的目標元素是否在頁面顯示。
#driver.find_element_by_xpath("//div/h3/a[text()='官網']/../a/em[text()='Selenium']").is_displayed()
#此處定位到element元素,然後取值,並不能寫成"//div/h3/a[text()='官網']/../a/em/text()"
result = driver.find_element_by_xpath("//div/h3/a[text()='官網']/../a/em").text
if result == "Selenium":
print("測試成功,結果和預期結果匹配!")
driver.quit()
else:
print("結果不符合預期")
總結:自動化測試最難的在於如何去寫斷言,如何判斷測試結果是否通過。