rev*_*evy 3 python beta selenium chrome-devtools-protocol
我已经从源代码构建并安装了Selenium 4.0.0-beta-1 python 轮来测试CDP功能。具体来说,我想使用Fetch Domain 协议拦截请求。
我可以使用命令启用域Fetch.enable,但我不知道如何订阅Fetch.requestPaused等事件来拦截请求:
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
driver = webdriver.Chrome()
# Enable Fetch domain
driver.execute_cdp_cmd('Fetch.enable', cmd_args={})
# How to subscribe to Fetch.requestPaused event??
# driver.add_cdp_event_listener ...
Run Code Online (Sandbox Code Playgroud)
谢谢你的帮助!
小智 9
使用 chromedriver v94 在 selenium 4.0.0rc1 上进行测试(最新截至 2021 年 9 月 21 日)。
import trio # async library that selenium uses
from selenium import webdriver
async def start_listening(listener):
async for event in listener:
print(event)
async def main():
driver = webdriver.Chrome()
async with driver.bidi_connection() as connection:
session, devtools = connection.session, connection.devtools
# await session.execute(devtools.fetch.enable())
await session.execute(devtools.network.enable())
# listener = session.listen(devtools.fetch.RequestPaused)
listener = session.listen(devtools.network.ResponseReceived)
async with trio.open_nursery() as nursery:
nursery.start_soon(start_listening, listener) # start_listening blocks, so we run it in another coroutine
driver.get('https://google.com')
trio.run(main)
Run Code Online (Sandbox Code Playgroud)
有几点需要注意:
Fetch.requestPaused不幸的是,目前它似乎不起作用。Fetch.enable发送命令并暂停请求,但似乎硒从未接收到该RequestPaused事件。(这就是代码片段使用的原因Network.responseReceived)devtools,但您仍然可以查看源 .py 文件以获取可用属性。更新:
Fetch.requestPaused现在可以使用。看一下示例:/sf/answers/5254717191/
它还支持更改 headers。