执行javascript代码思想chrome-dev工具协议



我正试图通过CDTP和PyChromeDevTools库执行一些javascript代码。以下代码有效:

来自终端:

/Applications/Google Chrome.app/Contents/MacOS/Google Chrome --remote-debugging-port=9222

import PyChromeDevTools
chrome.Network.enable()
chrome.Page.enable()
script="t='hi,';c='this code works on the same line';console.log(t,c)"
chrome.Runtime.evaluate(expression=script)

当我需要注入不在同一行的复杂js代码时,我遇到了一些麻烦,例如带有javascript请求的函数ecc。。

script="t='hi,';
c='this code works not on the same line don't work ';
console.log(t,c)"
chrome.Runtime.evaluate(expression=script)

是否可以将javascript文件等同于运行时评估?像这样:

chrome.Runtime.evaluate(expression=file.js)

CDTP 文件

https://chromedevtools.github.io/devtools-protocol/

您只需要将文件中的js代码加载到str变量中

def load_text(filename, mode='r', encoding='utf-8'):
with open(filename, mode, encoding=encoding) as f:
txt = f.read()
return txt
file_js = load_text('file.js')
chrome.Runtime.evaluate(expression=file_js)