如何在 google chrome 中从 HTML 运行 python 脚本?
P粉471207302
P粉471207302 2023-11-02 23:34:24
0
1
657

我正在构建一个 chrome 扩展程序,我想通过单击扩展程序(基本上是 HTML)中的按钮来运行我的 PC 中的 python 脚本。 python 脚本使用 selenium web-driver 从网站抓取数据并将其存储在另一个日志文件中。

P粉471207302
P粉471207302

全部回复(1)
P粉316110779

您基本上使用nativeMessaging。它允许您在扩展程序和外部进程(例如 python)之间创建通信桥梁。

nativeMessaging 的工作方式是在您的计算机,并通过 stdin 和 stdout 与 Chrome 扩展进行通信。例如:

使用 Python 托管

这就是您在 python 中编写 nativeMessaging 主机的方式,我已经包含了完整的示例来自文档,但使用更少的代码更容易理解。

主机.py

这基本上是一个回显服务器,尊重标准输入和标准输出,确保它作为二进制流发送。

#!/usr/bin/env python

import struct
import sys
import os, msvcrt

# Set the I/O to O_BINARY to avoid modifications from input/output streams.
msvcrt.setmode(sys.stdin.fileno(), os.O_BINARY)
msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)

# Helper function that sends a message to the webapp.
def send_message(message):
   # Write message size.
  sys.stdout.write(struct.pack('I', len(message)))
  # Write the message itself.
  sys.stdout.write(message)
  sys.stdout.flush()

# Thread that reads messages from the webapp.
def read_thread_func():
  message_number = 0
  while 1:
    # Read the message length (first 4 bytes).
    text_length_bytes = sys.stdin.read(4)

    if len(text_length_bytes) == 0:
      sys.exit(0)

    # Unpack message length as 4 byte integer.
    text_length = struct.unpack('i', text_length_bytes)[0]

    # Read the text (JSON object) of the message.
    text = sys.stdin.read(text_length).decode('utf-8')

    send_message('{"echo": %s}' % text)


def Main():
    read_thread_func()
    sys.exit(0)

if __name__ == '__main__':
  Main()

主机.json

这定义了通信 python 主机,确保扩展 guid 是您的扩展的 guid。

{
  "name": "com.google.chrome.example.echo",
  "description": "Chrome Native Messaging API Example Host",
  "path": "host.bat",
  "type": "stdio",
  "allowed_origins": [
    "chrome-extension://knldjmfmopnpolahpmmgbagdohdnhkik/"
  ]
}

主机.bat

这将运行 python 可执行文件。

@echo off
python "%~dp0/host.py" %*

安装主机.bat

您运行一次,以在操作系统中注册您的主机。

REG ADD "HKCU\Software\Google\Chrome\NativeMessagingHosts\com.google.chrome.example.echo" /ve /t REG_SZ /d "%~dp0host.json" /f

Chrome 扩展程序

manifest.json

添加nativeMessing的权限

{
  "permissions": [
    "nativeMessaging"
  ]
}

通信.js

为了连接到 python 主机,您需要执行以下操作:

const hostName = "com.google.chrome.example.echo";
let port = chrome.runtime.connectNative(hostName);
port.onMessage.addListener(onNativeMessage);
port.onDisconnect.addListener(onDisconnected);

要向您的 python 主机发送消息,只需向端口发送一个 json 对象即可。

const message = {"text": "Hello World"};
if (port) {
    port.postMessage(message);
}

要知道断开连接时的错误:

function onDisconnected() {
  port = null;
  console.error(`Failed to connect: "${chrome.runtime.lastError.message}"`);
}

这个完整的示例位于文档中,为了清楚起见,我只是重命名了一些内容,可用于 Windows/Unix https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/docs/examples/api/nativeMessaging

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!