microsoft / playwright-python

Python version of the Playwright testing and automation library.
https://playwright.dev/python/
Apache License 2.0
11.39k stars 866 forks source link

[Question]: how to listen webscoket #930

Closed zenghh closed 2 years ago

zenghh commented 2 years ago

Your question

when i run this to listen websocket, i just see websocket open msg

import time
from playwright.sync_api import sync_playwright

def run():
    playwright = sync_playwright().start()
    browser = playwright.firefox.launch(headless=False)
    context = browser.new_context()
    page = context.new_page()
    page.on("websocket", on_web_socket)
    page.goto("https://www.bet365.com/")

    while True:
        time.sleep(0.5)

def on_web_socket(ws):
    print(f"WebSocket opened: {ws.url}")
    ws.on("framesent", lambda payload: print(payload))
    ws.on("framereceived", lambda payload: print(payload))
    ws.on("close", lambda payload: print("WebSocket closed"))

if __name__ == "__main__":
    run()

and when i add page.wait_for_selector("aaaa", timeout=1000000) wai for an nonexist selector, i can listen all ws msg, but how can i listen all ws msg in an regular way

import time
from playwright.sync_api import sync_playwright

def run():
    playwright = sync_playwright().start()
    browser = playwright.firefox.launch(headless=False)
    context = browser.new_context()
    page = context.new_page()
    page.on("websocket", on_web_socket)
    page.goto("https://www.bet365.com/")
    page.wait_for_selector("aaaa", timeout=1000000)

    while True:
        time.sleep(0.5)

def on_web_socket(ws):
    print(f"WebSocket opened: {ws.url}")
    ws.on("framesent", lambda payload: print(payload))
    ws.on("framereceived", lambda payload: print(payload))
    ws.on("close", lambda payload: print("WebSocket closed"))

if __name__ == "__main__":
    run()
mxschmitt commented 2 years ago

The reason is that you are using time.sleep(). If you replace it with page.wait_for_timeout(500) it works as expected, see here for more information: https://playwright.dev/python/docs/intro#timesleep-leads-to-outdated-state