how keep function printing the websocket response using pyppeteer

355 views Asked by At

how i keep my async function opened priting a response from websocket? just like await asyncio.sleep(1000)

import asyncio
from pyppeteer import launch

async def main():
    browser = await launch(headless=True, autoClose=False)
    page = await browser.newPage()
    await page.setUserAgent('Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3542.0 Safari/537.36')
    await page.goto('about:blank')

    await page.evaluate('''() => {
    const ws = new WebSocket("wss://stream.binance.com:9443/ws/btceur@kline_15m");
    ws.addEventListener('open', (e) => {
            console.log("connected")
    })

    ws.addEventListener('message', (message) => {
            console.log(message.data)
    })

    ws.addEventListener('close', (message) => {
            console.log(message)
    })

    ws.addEventListener('error', (error) => {
            console.log(error);
    })
        }''')
        
    cdp = await page.target.createCDPSession()
    await cdp.send('Network.enable')
    await cdp.send('Page.enable')

    def printResponse(response):
        print(response)
    cdp.on('Network.webSocketFrameReceived', printResponse)  # Calls printResponse when a websocket is received
    await asyncio.sleep(1000)

loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
loop.run_until_complete(main())
0

There are 0 answers