記錄一下
背景:
有個同事想要獲取項目產(chǎn)品上的一些數(shù)據(jù)蔑舞,但是產(chǎn)品并沒有提供相應(yīng)的獲取數(shù)據(jù)的接口。所以這個同事想要抓取請求鏈接進行數(shù)據(jù)獲取筷弦,但是從F12中抓取的請求中需要有一個Authorization的header數(shù)據(jù),但是F12上沒有獲取到生成這個Authorization的接口,猜想這個數(shù)據(jù)可能直接在代碼中生成的斥滤。所以現(xiàn)在的問題是如何獲取Authorization的值。
在經(jīng)過一系列考慮后轿秧,最后決定最開始使用selenium+browsermob-proxy的方式獲取到一個請求接口的Authorization值中跌,之后就可以直接使用接口進行請求獲取想要的數(shù)據(jù)了。
browsermob-proxy
BrowserMob Proxy是一個用戶操作瀏覽器代理的工具菇篡,它可以用于記錄和分析HTTP請求和響應(yīng)漩符。主要用途之一是用于自動化測試,例如本文所寫驱还。
browsermob-proxy的安裝
1. 下載browsermob-proxy.bat
2.安裝python模塊browsermob-proxy
?pip install?browsermob-proxy
具體使用
第一步:開啟代理
第二步:
第三步:關(guān)閉BrowserMob Proxy和selenium
完整代碼
from browsermobproxyimport Server
from seleniumimport webdriver
from selenium.webdriver.chrome.optionsimport Options
bmp_path =r"browsermob-proxy.bat的路徑"
server = Server(bmp_path)
server.start()
proxy = server.create_proxy()
# 配置Selenium使用BrowserMob Proxy
chrome_options = Options()
chrome_options.add_argument("--proxy-server={0}".format(proxy.proxy))
chrome_options.add_experimental_option('excludeSwitches', ['enable-automation'])
chrome_options.add_argument("--ignore-certificate-errors")#解決:您的連接不是私密連接
# 初始化WebDriver
driver = webdriver.Chrome(executable_path=r'chromedriver.exe的路徑', options=chrome_options)
# 設(shè)置一個新的Har來捕獲請求
proxy.new_har("test", options={'captureHeaders':True, 'captureContent':True})
driver.get("****網(wǎng)站鏈接****")
#重要:此處操作為對目標頁面的一些操作
#例如我這邊需要使用selenium到對應(yīng)要獲取數(shù)據(jù)的網(wǎng)站上嗜暴,然后打開一個可以獲取到Authorization的頁面
driver.find_element_by_id("username").send_keys("****")
driver.find_element_by_id("password").send_keys("*****")
driver.find_element_by_id("submit_psd").click()
driver.get("*****/productManage")
# 獲取HAR數(shù)據(jù)
har = proxy.har
# 遍歷HAR中的請求并查找Auth字段
for entryin har['log']['entries']:
request = entry['request']
url = request['url']
if "pageList" in url:
headers = request['headers']
for hin headers:
if h.get("name")=="Authorization":
auth = h["value"]#這個是Authorization
? ? ? ? ? ? ? ? print(auth)
# 關(guān)閉BrowserMob Proxy和Selenium
server.stop()
driver.quit()