简体   繁体   中英

Using remote chrome devtools from Python

I want to use the remote socket debugging stuff for Chrome devtools ( link ) from Python. I'm using code adapted from here .

I've managed to get ping and list_tabs working. But I can't figure out how to evaluate_javascript . Can anybody tell me what I'm doing wrong?

import subprocess
import time, json, socket

from jca.files import my_paths

def request(tool, destination=None, **kw):
  # Send a command via socket to 'DevToolsService' or 'V8Debugger'
  j = json.dumps(kw)
  request = 'Content-Length:%d\r\nTool:%s\r\n' % (len(j), tool)
  if destination:
    request += 'Destination:%s\r\n' % (destination,)
  request += '\r\n%s\r\n' % (j,)
  sock.send(request)
  if kw.get('command', '') not in RESPONSELESS_COMMANDS:
    time.sleep(.1)
    response = sock.recv(30000)
    if response.strip():
      j = response.split('\r\n\r\n', 1)[1]
      return json.loads(j)

if __name__ == '__main__':
  proc = subprocess.Popen('"%s" --remote-shell-port=9222' % my_paths.chrome_exe)
  RESPONSELESS_COMMANDS = ['evaluate_javascript']
  sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  sock.connect(('localhost', 9222))
  sock.send('ChromeDevToolsHandshake\r\n')
  result = sock.recv(1024)
  print 'ping: ', request('DevToolsService', command='ping')
  time.sleep(4)
  print 'list_tabs: ', request('DevToolsService', command='list_tabs')
  request('V8Debugger', command='evaluate_javascript', 
          data='javascript:window.location.reload()')
  sock.close()
  print 'done'

I'm sorry for spam, there's a Java library for this: http://code.google.com/p/chromedevtools/

Since you probably chosen Python not at random, you could have it as a reference implementation if running Java code is OK for you. I guess you could check the actual messages sent and received from Java debugger.

The problem was that I didn't set a tab_id for destination. Adding destination=2 to the request call fixes the problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM