Selenium執行cdp命令,driver.execute_cdp_cmd用法

Chrome自帶的開發者工具DevTools功能很是強大。有時候咱們在使用Selenium操做瀏覽器時須要經過調用一下DevTools的方法來完成一些設置,如模擬移動設備,弱網模擬等等。 Selenium的WebDriver類中有一個execute_cdp_cmd(self, cmd, cmd_args)方法能夠用來執行Chrome開發這個工具命令。python

cdp即Chrome DevTools Protocal, Chrome開發者工具協議,API文檔可參考:https://chromedevtools.github.io/devtools-protocol/tot/Emulationgit

使用方法,示例:github

import requests
from selenium import webdriver
from time import sleep
import base64

driver = webdriver.Chrome()
driver.get('https://www.hao123.com/')

res = driver.execute_cdp_cmd('Page.captureScreenshot', {})

with open('hao123.png', 'wb') as f:
    img = base64.b64decode(res['data'])
    f.write(img)

sleep(3)
driver.quit()

這個例子是調用cdp中Page類的截圖方法,支持png格式和jpeg格式,調用後返回的數據data字段中爲圖片的base64編碼,將編碼解碼成二進制後能夠保持爲圖片。web

很遺憾的是,雖然Chrome開發者工具前臺命令菜單中有Capture full screenshot的命令,以下圖,但cdp的方法中無此方法,Selenium3後全部的瀏覽器都沒法全屏截圖。 chrome

相關文章
相關標籤/搜索