同样通过playrwright拉起本地浏览器跳转到对应页面,对页面中的websocket进行监听。
以websocket测试网站:http://www.websocket-test.com/为例,实现对其中的websocket进行监听,代码如下:
from playwright.sync_api import sync_playwright as playwright
def onmessage(data):
print(f'接收消息:{data}')
def send(data):
print(f'发送消息:{data}')
def close(data):
print(f'链接断开{data}')
def websocket_callback(wss):
print("websocket的url:", wss.url)
wss.on('framereceived', onmessage) # 监听服务端发送的websocket消息
wss.on('framesent', send) # 监听客户端发送的websocket消息
wss.on('close', close) # 监听关闭websocket链接
with playwright() as pw:
# 调用本地浏览器
browser = pw.chromium.launch_persistent_context( # 调用本地安装的浏览器
# chrome://version/
# 缓存地址
user_data_dir=r'C:\Users\XF\AppData\Local\Google\Chrome\User Data',
# 启动路径
executable_path=r'C:\Program Files\Google\Chrome\Application\chrome.exe',
# 关闭无头模式
headless=False,
# 跳过检测
args=['--disable-blink-features=AutomationControlled', '--enable-automation']
)
page = browser.new_page()
page.on('websocket', websocket_callback)
page.goto('http://www.websocket-test.com/') # 跳转到websocket测试网站
# 浏览器保持开启状态
page.wait_for_timeout(1000000000)
运行结果:
此处评论已关闭