You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

USB RFID读卡器触发自动打开HTML并填充NFC ID表单及pynput报错求助

问题:解决pynput模块找不到的问题并实现RFID读卡器触发HTML自动填充功能

需求说明

  • 编写后台运行脚本,当USB RFID读卡器(键盘模拟模式)检测到卡片时,自动打开指定HTML文件
  • 将RFID数据自动填入HTML中的NFC ID表单

现有代码(无法正常运行)

import pynput
from pynput.keyboard import Key, Listener
import webbrowser
import time

# Set up the keyboard listener
def on_press(key):
    try:
        # Check if the key press is from the RFID reader (e.g., a string of digits)
        if key.char.isdigit():
            # Get the RFID data (assuming it's a single string of digits)
            rfid_data = ''
            while True:
                key = keyboard.read_key()
                if key == Key.enter:
                    break
                rfid_data += key.char
            print(f"RFID data: {rfid_data}")

            # Open the HTML file
            webbrowser.open('upload-data\html-web-upload.html')

            # Optionally, input the RFID data into a form on the HTML file
            # using selenium or another library
            #...

    except AttributeError:
        pass

def on_release(key):
    if key == Key.esc:
        # Stop the listener when the Esc key is pressed
        return False

# Create a keyboard listener
with Listener(on_press=on_press, on_release=on_release) as listener:
    listener.join()

报错信息

File "c:\xampp\htdocs\switch_ditekan\script_nfc.py", line 1, in <module>
    import pynput
ModuleNotFoundError: No module named 'pynput'

解决步骤

1. 修复pynput模块找不到的问题

问题出在VS Code使用的Python环境和你用cmd执行pip install的环境不一致,按以下操作解决:

  • 打开VS Code,左下角状态栏会显示当前使用的Python版本/环境,点击它选择你在cmd中使用的那个Python环境
  • 打开VS Code终端(快捷键Ctrl+),直接执行pip install pynput`,确保模块安装到当前VS Code使用的环境中
  • 验证:在终端执行python -c "import pynput; print('安装成功')",无报错则说明安装正常

2. 代码逻辑优化(原代码存在嵌套监听的错误)

以下是修复逻辑并实现表单填充的完整代码:

from pynput.keyboard import Key, Listener
import webbrowser
import time
from selenium import webdriver
from selenium.webdriver.common.by import By

# 用于暂存RFID输入的数字
rfid_buffer = []

def on_press(key):
    try:
        # 收集读卡器输入的数字字符
        if key.char.isdigit():
            rfid_buffer.append(key.char)
        # 读卡器通常会以Enter键结束输入,此时处理数据
        elif key == Key.enter and rfid_buffer:
            rfid_data = ''.join(rfid_buffer)
            print(f"读取到RFID数据: {rfid_data}")
            rfid_buffer.clear()
            
            # 用file协议打开本地HTML文件(替换成你的实际路径)
            html_full_path = 'file:///c:/xampp/htdocs/switch_ditekan/upload-data/html-web-upload.html'
            webbrowser.open(html_full_path)
            
            # 等待页面加载,然后用Selenium填充表单
            time.sleep(2)
            # 这里用ChromeDriver,需提前下载对应版本的驱动并配置到系统PATH
            driver = webdriver.Chrome()
            driver.get(html_full_path)
            # 替换成你HTML中NFC ID表单的实际选择器(比如id、name)
            nfc_input = driver.find_element(By.ID, "nfc-id")
            nfc_input.send_keys(rfid_data)
            
    except AttributeError:
        # 忽略非字符类按键(如功能键)
        pass

def on_release(key):
    if key == Key.esc:
        # 按Esc键停止脚本运行
        return False

# 启动键盘监听
with Listener(on_press=on_press, on_release=on_release) as listener:
    listener.join()

额外注意事项

  • 要使用Selenium自动填充表单,需先安装selenium库:pip install selenium
  • 需下载对应浏览器的驱动(如ChromeDriver),并将驱动所在路径添加到系统PATH中
  • HTML文件路径建议使用绝对路径的file协议格式,避免相对路径解析错误

内容的提问来源于stack exchange,提问作者Tyven Christopher

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 10:12:34