首頁  >  問答  >  主體

如何在 google chrome 中從 HTML 執行 python 腳本?

我正在建立一個 chrome 擴充程序,我想透過點擊擴充功能(基本上是 HTML)中的按鈕來運行我的 PC 中的 python 腳本。 python 腳本使用 selenium web-driver 從網站抓取資料並將其儲存在另一個日誌檔案中。

P粉471207302P粉471207302351 天前1002

全部回覆(1)我來回復

  • P粉316110779

    P粉3161107792023-11-03 14:40:52

    您基本上使用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< /a>

    回覆
    0
  • 取消回覆