Requestium - 將Requests和Selenium合并在一起的自動化測試工具
1、前言
Requests 是 Python 的第三方庫,主要用于發(fā)送 http 請求,常用于接口自動化測試等。
Selenium 是一個用于 Web 應(yīng)用程序的自動化測試工具。Selenium 測試直接運行在瀏覽器中,就像真正的用戶在操作一樣。
本篇介紹一款將 Requests 和 Selenium 結(jié)合在一起的自動化測試工具 - Requestium
2、簡介
Requestium 是一個 Python 庫,它將 Requests、Selenium 和 Parsel 的功能合并為一個用于自動化 web 操作的集成工具。
該庫是為編寫 web 自動化腳本而創(chuàng)建的,這些腳本主要使用請求編寫,但能夠在維護(hù)會話的同時,無縫切換到網(wǎng)站中 JavaScript 密集部分的 Selenium。
Requestium 為 Requests 和 Selenium 添加了獨立的改進(jìn),并且每一個新功能都經(jīng)過了延遲評估,因此即使編寫只使用 Requests 或 Selenium 的腳本,它也很有用。
特點:
- 在維護(hù)當(dāng)前 web 會話的同時,啟用請求會話和 Selenium web 驅(qū)動程序之間的切換。
- 將 Parsel 的解析器集成到庫中,使 xpath、css 和 regex 的編寫更加簡潔。
- 改進(jìn)了 Selenium 對動態(tài)加載元素的處理。
- 使 Selenium 中的 cookie 處理更加靈活。
- 使 Selenium 中的點擊元素更加可靠。
- 本機支持 Chromedriver,并添加自定義網(wǎng)絡(luò)驅(qū)動程序。
安裝:
pip install requestium
如果你使用 Requestium 的 Selenium 部分,例如 Chromedriver,那么你應(yīng)該下載 Selenium Web 驅(qū)動程序。
3、快速上手
首先,像處理請求一樣創(chuàng)建一個會話,如果使用 web 驅(qū)動程序,可以選擇添加參數(shù)。
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 公眾號:AllTests軟件測試
from requestium import Session, Keys
options = {'arguments': ['headless']}
s = Session(webdriver_path='./chromedriver', default_timeout=15, webdriver_options=options)
由于無頭模式很常見,因此有一個快捷方式可以指定 headless=True。
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 公眾號:AllTests軟件測試
from requestium import Session, Keys
s = Session(webdriver_path='./chromedriver' headless=True)
你也可以在 Requestium 之外創(chuàng)建一個 Selenium 網(wǎng)絡(luò)驅(qū)動程序,并使用它:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 公眾號:AllTests軟件測試
from selenium import webdriver
from requestium import Session, Keys
firefox_driver = webdriver.Firefox()
s = Session(driver=firefox_driver)
你不需要解析響應(yīng),當(dāng)調(diào)用 xpath,css 或 re 時,它會自動完成。
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 公眾號:AllTests軟件測試
title = s.get('http://samplesite.com').xpath('//title/text()').extract_first(default='Default Title')
與 Python 的標(biāo)準(zhǔn) re 模塊相比,正則表達(dá)式需要更少的代碼。
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 公眾號:AllTests軟件測試
response = s.get('http://samplesite.com/sample_path')
# Extracts the first match
identifier = response.re_first(r'ID_\d\w\d', default='ID_1A1')
# Extracts all matches as a list
users = response.re(r'user_\d\d\d')
你可以切換到使用 Selenium Webdriver 來運行任何 js 代碼。
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 公眾號:AllTests軟件測試
s.transfer_session_cookies_to_driver()
s.driver.get('http://www.samplesite.com/sample/process')
最后,你可以切換回使用 Requests。
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 公眾號:AllTests軟件測試
s.transfer_driver_cookies_to_session()
s.post('http://www.samplesite.com/sample2', data={'key1': 'value1'})
等待元素
ensure_element_by_ 方法等待元素在瀏覽器中加載,并在加載后立即返回。它以 Selenium的 find_element_by_ 方法命名(如果找不到元素,它們會立即引發(fā)異常)。
Requestium 可以等待一個元素處于以下任何狀態(tài):
- 存在(默認(rèn))
- 可點擊
- 看得見的
- 不可見(可用于等待加載... GIF 消失等)
這些方法對于單頁面 Web 應(yīng)用程序非常有用,其中站點動態(tài)地更改其元素。我們通常最終完全用 ensure_element_by_ 調(diào)用替換我們的 find_element_by_ 調(diào)用,因為它們更靈活。使用這些方法獲取的元素具有新的 ensure_click 方法,這使得點擊不太容易失敗。這有助于解決 Selenium 點擊的許多問題。
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 公眾號:AllTests軟件測試
s.driver.ensure_element_by_xpath("http://li[@class='b1']", state='clickable', timeout=5).ensure_click()
# === We also added these methods named in accordance to Selenium's api design ===
ensure_element_by_id
ensure_element_by_name
ensure_element_by_link_text
ensure_element_by_partial_link_text
ensure_element_by_tag_name
ensure_element_by_class_name
ensure_element_by_css_selector
添加 Cookie
ensure_add_cookie 方法使得添加 Cookie 更加穩(wěn)健。Selenium 需要瀏覽器在能夠添加 Cookie 之前處于 Cookie 的域中,此方法為此提供了幾種解決方法。如果瀏覽器不在 Cookie 域中,它會先獲取域然后再添加 Cookie。它還允許你在添加 Cookie 之前覆蓋域,并避免執(zhí)行此 GET。域可以被覆蓋為 ’’,這將把 Cookie 的域設(shè)置為驅(qū)動程序當(dāng)前所在的任何域。如果無法添加 cookie,它會嘗試使用限制性較小的域(例如:home.site.com -> site.com)進(jìn)行添加,然后在失敗之前。
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 公眾號:AllTests軟件測試
cookie = {"domain": "www.site.com",
"secure": false,
"value": "sd2451dgd13",
"expiry": 1516824855.759154,
"path": "/",
"httpOnly": true,
"name": "sessionid"}
s.driver.ensure_add_cookie(cookie, override_domain='')
使用 Requestium 示例
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 公眾號:AllTests軟件測試
from requestium import Session, Keys
# If you want requestium to type your username in the browser for you, write it in here:
reddit_user_name = ''
s = Session('./chromedriver', default_timeout=15)
s.driver.get('http://reddit.com')
s.driver.find_element_by_xpath("http://a[@).click()
print('Waiting for elements to load...')
s.driver.ensure_element_by_class_name("desktop-onboarding-sign-up__form-toggler",
state='visible').click()
if reddit_user_name:
s.driver.ensure_element_by_id('user_login').send_keys(reddit_user_name)
s.driver.ensure_element_by_id('passwd_login').send_keys(Keys.BACKSPACE)
print('Please log-in in the chrome browser')
s.driver.ensure_element_by_class_name("desktop-onboarding__title", timeout=60, state='invisible')
print('Thanks!')
if not reddit_user_name:
reddit_user_name = s.driver.xpath("http://span[@class='user']//text()").extract_first()
if reddit_user_name:
s.transfer_driver_cookies_to_session()
response = s.get("https://www.reddit.com/user/{}/".format(reddit_user_name))
cmnt_karma = response.xpath("http://span[@class='karma comment-karma']//text()").extract_first()
reddit_golds_given = response.re_first(r"(\d+) gildings given out")
print("Comment karma: {}".format(cmnt_karma))
print("Reddit golds given: {}".format(reddit_golds_given))
else:
print("Couldn't get user name")