如何从谷歌浏览器中的HTML运行python脚本?

Ayu*_*mar 0 javascript python selenium google-chrome-extension flask

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

Moh*_*our 5

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

nativeMessaging的工作方式是在计算机上安装主机,然后通过stdin和stdout与Chrome扩展进行通讯。例如:

使用Python托管

这就是您用python 编写nativeMessaging主机的方式,我已经从docs中获得了完整的示例,但是使用更少的代码就更容易理解。

host.py

这基本上是一个回显服务器,尊重stdin和stdout,确保将其作为二进制流发送。

#!/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()
Run Code Online (Sandbox Code Playgroud)

host.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/"
  ]
}
Run Code Online (Sandbox Code Playgroud)

主机

这将运行python可执行文件。

@echo off
python "%~dp0/host.py" %*
Run Code Online (Sandbox Code Playgroud)

install_host.bat

您只需运行一次,即可在操作系统中注册主机。

REG ADD "HKCU\Software\Google\Chrome\NativeMessagingHosts\com.google.chrome.example.echo" /ve /t REG_SZ /d "%~dp0host.json" /f
Run Code Online (Sandbox Code Playgroud)

Chrome扩展程序

manifest.json

为添加权限 nativeMessing

{
  "permissions": [
    "nativeMessaging"
  ]
}
Run Code Online (Sandbox Code Playgroud)

communication.js

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

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

要将消息发送到python主机,只需将json对象发送到端口。

const message = {"text": "Hello World"};
if (port) {
    port.postMessage(message);
}
Run Code Online (Sandbox Code Playgroud)

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

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

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