- selenium定義:
Selenium 是開源的自動化測試工具,它主要是用于Web 應(yīng)用程序的自動化測試稚铣,不只局限于此碾篡,同時支持所有基于web 的管理任務(wù)自動化驼卖。
環(huán)境準(zhǔn)備:
下載chromedriver,將下載的exe文件放在python安裝根目錄莺治,若放在其他目錄需要在PATH環(huán)境變量中添加該地址廓鞠。常用的參數(shù):
參數(shù) | 說明 |
---|---|
'start-maximized' | 瀏覽器窗口最大化 |
'incognito' | 無痕模式 |
'useAutomationExtension', False & "excludeSwitches", ['enable-automation'] | 關(guān)閉左上方Chrome正在受到自動測試軟件的控制的提示 |
'headless' | 無界面運行 |
'window-size= 800,600' | 設(shè)置瀏覽器窗口大小 |
- 8種定位元素的方式:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys #提供了鍵盤的代碼(回車帚稠,ALT等)
opt = webdriver.ChromeOptions()
opt.add_argument('start-maximized')
driver = webdriver.Chrome(options=opt)
driver.get('https://www.baidu.com/')
driver.find_element(By.ID,'kw').send_keys('By ID')
driver.find_element(By.NAME,'wd').send_keys('By NAME')
driver.find_element(By.LINK_TEXT,'新聞').click()
list = driver.find_element(By.PARTIAL_LINK_TEXT,'百度').click()
driver.find_element(By.XPATH,'//*[@id="kw"]').send_keys('By XPATH')
driver.find_element(By.CLASS_NAME,'s_ipt').send_keys('By CLASS_NAME')
driver.find_element(By.CSS_SELECTOR,'#kw').send_keys('By CSS_SELECTOR')
tags = driver.find_elements(By.TAG_NAME,'input')
for t in tags:
if t.get_attribute('type') == 'text' and t.get_attribute('class') == 's_ipt':
t.send_keys('By Tag_name')
- 定位彈窗:
a = driver.switch_to.alert # 定位到窗口
print(a.text) # 打印文本信息
a.accept() # 點擊alert確認按鈕
- 切換到子框架:
driver.switch_to.frame('iframe的Id或Name') # 切換框架
drive.switch_to.default_content() # 退出框架
- cookies:
driver.get_cookie('remember_user_token') # 獲取某項cookie的值
driver.get_cookies() # 獲取所有cookie
driver.add_cookie(cookie) # 添加cookie
- 保持網(wǎng)頁截圖:
driver.get_screenshot_as_file('test.png')
- 顯式等待和隱式等待:
#這段代碼會等待10秒,如果10秒內(nèi)找到元素則立即返回床佳,否則會拋出TimeoutException異常滋早,WebDriverWait默認每500毫秒調(diào)用一下ExpectedCondition直到它返回成功為止。
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions
WebDriverWait(driver,10).until(expected_conditions.element_to_be_clickable((By.ID,'main'))) #等待一個確定的條件觸發(fā)然后才進行更深一步的執(zhí)行
#隱式等待
drive.implicitly_wait(10) # seconds
使用Selenium測試:
import unittest
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys #提供了鍵盤的代碼(回車砌们,ALT等)
'''
參考文檔:https://python-selenium-zh.readthedocs.io/zh_CN/latest/
'''
class PythonOrgSearch(unittest.TestCase):
def setUp(self): #初始化
self.driver = webdriver.Chrome()
def test_search_python(self): #測試用例的方法需要以test開頭
driver = self.driver
driver.get('http://www.python.org') #等待頁面加載完(就是onload函數(shù)被觸發(fā)了)
assert 'Python' in driver.title #斷言用來判斷一個表達式杆麸,在表達式為false的時候觸發(fā)異常
ele = driver.find_element(By.NAME,'q')
ele.send_keys('python')
ele.send_keys(Keys.RETURN)
assert 'No results found' not in driver.page_source #用斷言來判斷是否有返回
def tearDown(self) -> None:
self.driver.quit() #close是關(guān)閉標(biāo)簽,而quit會退出整個瀏覽器
if __name__ == '__main__':
unittest.main()