【轉】chrome devtools protocol——Web 效能自動化
阿新 • • 發佈:2018-11-05
前言
在測試Web頁面載入時間時,可能會是這樣的:
- 開啟chrome瀏覽器。
- 按F12開啟開發者工具。
- 在瀏覽器上開啟要測試的頁面
- 檢視開發者工具中Network面板的頁面效能資料並記錄
- 或者在開發者工具中Console面板執行
performance.timing
和performance.getEntries()
收集資料
performance相關資訊看這裡PerformanceTiming
幾十上百個頁面,每個版本都這樣來,估計瘋了,所以就想怎麼把它做成自動化呢?
chrome devtools protocol
chrome devtools protocol允許第三方對基於chrome的web應用程式進行除錯、分析等,它基於WebSocket,利用WebSocket建立連線DevTools和瀏覽器核心的快速資料通道。一句話,有了這個協議就可以自己開發工具獲取chrome的資料
協議詳細內容看這裡chrome devtools protocol
目前已經有很多大神針對這個協議封裝出不同語言(nodejs,python,java...)的庫,詳細資訊看這裡awesome-chrome-devtools
這邊我選擇的是python的pychrome github地址,使用方法很簡單,直接看github上它的Demo
這個庫依賴websocket-client
獲取performance api資料
這裡使用Runtime Domain中執行JavaScript指令碼的APIRuntime.evaluate
# 開始前先啟動chrome,啟動chrome必須帶上引數`--remote-debugging-port=9222`開啟遠端除錯否則無法與chrome互動
browser = pychrome.Browser('http://127.0.0.1:%d' % 9222)
tab = browser.new_tab()
tab.start()
tab.Runtime.enable()
tab.Page.navigate(url={你的頁面地址})
# 設定等待頁面載入完成的時間
tab.wait(10)
# 執行js指令碼
timing_remote_object = tab.Runtime.evaluate(
expression='performance.timing'
)
# 獲取performance.timing結果資料
timing_properties = tab.Runtime.getProperties(
objectId=timing_remote_object.get('result').get('objectId')
)
timing = {}
for item in timing_properties.get('result'):
if item.get('value', {}).get('type') == 'number':
timing[item.get('name')] = item.get('value').get('value')
# 獲取performance.getEntries()資料
entries_remote_object = tab.Runtime.evaluate(
expression='performance.getEntries()'
)
entries_properties = tab.Runtime.getProperties(
objectId=entries_remote_object.get('result').get('objectId')
)
entries_values = []
for item in entries_properties.get('result'):
if item.get('name').isdigit():