Selenium 自動登錄網(wǎng)站、截圖及 Requests 抓取登錄后的網(wǎng)頁內(nèi)容。一起了解下吧。
- Selenium: 支持 Web 瀏覽器自動化的一系列工具和庫的綜合項目。
- Requests: 唯一的一個非轉(zhuǎn)基因的 Python HTTP 庫,人類可以安全享用。
?
為什么選擇 Selenium 實現(xiàn)自動登錄?
Selenium 實現(xiàn),相當(dāng)于模擬用戶手動打開瀏覽器、進行登錄的過程。
相比直接 HTTP 請求登錄,有幾個好處:
- 避免登錄窗口的復(fù)雜情況(iframe, ajax 等),省得分析細節(jié)。
- 用 Selenium 實現(xiàn),依照用戶操作流程即可。
- 避免模擬 Headers 、記錄 Cookies 等 HTTP 完成登錄的細節(jié)。
- 用 Selenium 實現(xiàn),依賴瀏覽器自身功能即可。
- 利于實現(xiàn)加載等待、發(fā)現(xiàn)特殊情況(登錄驗證等),加進一步邏輯。
另外,自動登錄等過程的可視化,給外行看挺讓人感覺高端的。
為什么選擇 Requests 抓取網(wǎng)頁內(nèi)容?
抓取登錄后的某些內(nèi)容,而非爬取網(wǎng)站, Requests 夠用、好用。
1) 準(zhǔn)備 Selenium
基礎(chǔ)環(huán)境: Python 3.7.4 (anaconda3-2019.10)
pip 安裝 Selenium :
pip install selenium
復(fù)制代碼
獲取 Selenium 版本信息:
$ python
Python 3.7.4 (default, Aug 13 2019, 15:17:50)
[Clang 4.0.1 (tags/RELEASE_401/final)] :: Anaconda, Inc. on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import selenium
>>> print('Selenium version is {}'.format(selenium.__version__))
Selenium version is 3.141.0
復(fù)制代碼
2) 準(zhǔn)備瀏覽器及其驅(qū)動
下載 Google Chrome 瀏覽器并安裝: www.google.com/chrome/
下載 Chromium/Chrome WebDriver: chromedriver.storage.googleapis.com/index.html
然后,將 WebDriver 路徑加入到 PATH ,例如:
# macOS, Linux
export PATH=$PATH:/opt/WebDriver/bin >> ~/.profile
# Windows
setx /m path "%path%;C:\WebDriver\bin\"
復(fù)制代碼
3) Go coding!
讀取登錄配置
登錄信息是私密的,我們從 json 配置讀?。?/p>
# load config
import json
from types import SimpleNamespace as Namespace
secret_file = 'secrets/douban.json'
# {
# "url": {
# "login": "https://www.douban.com/",
# "target": "https://www.douban.com/mine/"
# },
# "account": {
# "username": "username",
# "password": "password"
# }
# }
with open(secret_file, 'r', encoding='utf-8') as f:
config = json.load(f, object_hook=lambda d: Namespace(**d))
login_url = config.url.login
target_url = config.url.target
username = config.account.username
password = config.account.password
復(fù)制代碼
Selenium 自動登錄
以 Chrome WebDriver 實現(xiàn),登錄測試站點為「豆瓣」。
打開登錄頁面,自動輸入用戶名、密碼,進行登錄:
# automated testing
from selenium import webdriver
# Chrome Start
opt = webdriver.ChromeOptions()
driver = webdriver.Chrome(options=opt)
# Chrome opens with “Data;” with selenium
# https://stackoverflow.com/questions/37159684/chrome-opens-with-data-with-selenium
# Chrome End
# driver.implicitly_wait(5)
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
wait = WebDriverWait(driver, 5)
print('open login page ...')
driver.get(login_url)
driver.switch_to.frame(driver.find_elements_by_tag_name("iframe")[0])
driver.find_element_by_css_selector('li.account-tab-account').click()
driver.find_element_by_name('username').send_keys(username)
driver.find_element_by_name('password').send_keys(password)
driver.find_element_by_css_selector('.account-form .btn').click()
try:
wait.until(EC.presence_of_element_located((By.ID, "content")))
except TimeoutException:
driver.quit()
sys.exit('open login page timeout')
復(fù)制代碼
如果用 IE 瀏覽器,如下:
# Ie Start
# Selenium Click is not working with IE11 in Windows 10
# https://github.com/SeleniumHQ/selenium/issues/4292
opt = webdriver.IeOptions()
opt.ensure_clean_session = True
opt.ignore_protected_mode_settings = True
opt.ignore_zoom_level = True
opt.initial_browser_url = login_url
opt.native_events = False
opt.persistent_hover = True
opt.require_window_focus = True
driver = webdriver.Ie(options = opt)
# Ie End
復(fù)制代碼
如果設(shè)定更多功能,可以:
cap = opt.to_capabilities()
cap['acceptInsecureCerts'] = True
cap['javascriptEnabled'] = True
復(fù)制代碼
打開目標(biāo)頁面,進行截圖
print('open target page ...')
driver.get(target_url)
try:
wait.until(EC.presence_of_element_located((By.ID, "board")))
except TimeoutException:
driver.quit()
sys.exit('open target page timeout')
# save screenshot
driver.save_screenshot('target.png')
print('saved to target.png')
復(fù)制代碼
Requests 復(fù)刻 Cookies ,請求 HTML
# save html
import requests
requests_session = requests.Session()
selenium_user_agent = driver.execute_script("return navigator.userAgent;")
requests_session.headers.update({"user-agent": selenium_user_agent})
for cookie in driver.get_cookies():
requests_session.cookies.set(cookie['name'], cookie['value'], domain=cookie['domain'])
# driver.delete_all_cookies()
driver.quit()
resp = requests_session.get(target_url)
resp.encoding = resp.apparent_encoding
# resp.encoding = 'utf-8'
print('status_code = {0}'.format(resp.status_code))
with open('target.html', 'w+') as fout:
fout.write(resp.text)
print('saved to target.html')
復(fù)制代碼
4) 運行測試
可以臨時將 WebDriver 路徑加入到 PATH :
# macOS, Linux
export PATH=$(pwd)/drivers:$PATH
# Windows
set PATH=%cd%\drivers;%PATH%
復(fù)制代碼
運行 Python 腳本,輸出信息如下:
$ python douban.py
Selenium version is 3.141.0
--------------------------------------------------------------------------------
open login page ...
open target page ...
saved to target.png
status_code = 200
saved to target.html
復(fù)制代碼
截圖 target.png
, HTML 內(nèi)容 target.html
,結(jié)果如下:
?
結(jié)語
登錄過程如果遇到驗證呢?
- 滑動驗證,可以 Selenium 模擬
- 滑動距離,圖像梯度算法可判斷
- 圖文驗證,可以 Python AI 庫識別
??今天的分享就到此結(jié)束了 ,如果文章對你有幫助,記得點贊,收藏,加關(guān)注。會不定期分享一些干貨哦......
最后感謝每一個認真閱讀我文章的人,看著粉絲一路的上漲和關(guān)注,禮尚往來總是要有的,雖然不是什么很值錢的東西,如果你用得到的話可以直接拿走:
下方這份完整的軟件測試視頻學(xué)習(xí)教程已經(jīng)上傳CSDN官方認證的二維碼,朋友們?nèi)绻枰梢宰孕忻赓M領(lǐng)取 【保證100%免費】
這些對想從事【軟件測試】的朋友來說應(yīng)該是最全面最完整的備戰(zhàn)倉庫,這個倉庫也陪伴我走過了最艱難的路程,希望也能幫助到你!凡事要趁早,特別是技術(shù)行業(yè),一定要提升技術(shù)功底。希望對大家有所幫助……基礎(chǔ)知識、Linux必備、Shell、互聯(lián)網(wǎng)程序原理、Mysql數(shù)據(jù)庫、抓包工具專題、接口測試工具、測試進階-Python編程、Web自動化測試、APP自動化測試、接口自動化測試、測試高級持續(xù)集成、測試架構(gòu)開發(fā)測試框架、性能測試、安全測試等配套學(xué)習(xí)資源免費分享~文章來源:http://www.zghlxwxcb.cn/news/detail-809961.html
文章來源地址http://www.zghlxwxcb.cn/news/detail-809961.html
到了這里,關(guān)于自動化測試: Selenium 自動登錄授權(quán),再 Requests 請求內(nèi)容的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!