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

Python exe传参方法及Selenium代码打包exe运行无响应排查

WhatsApp Selenium Automation EXE Not Running & Parameter Passing Guide

Problem Statement

我已将以下基于Selenium的WhatsApp自动化代码打包为exe文件,生成了/dist目录,但运行该exe时无任何反应。请问我的操作是否有误?能否通过exe运行该代码?请给出解决建议。同时想了解如何给Python生成的exe文件传递参数。

代码如下:

from selenium import webdriver
from time import sleep
import sys
driver = webdriver.Firefox() # To connect to web browser use webdriver imported from selenium
driver.get('https://web.whatsapp.com/')
name = sys.argv[1]
msg = sys.argv[2]
filepath = sys.argv[3]
def whatsapp(name, msg="", filepath=""):
    input('Enter anything after scanning QR code')
    user = driver.find_element_by_xpath('//span[@title = "{}"]'.format(name))
    user.click()
    if msg != "":
        msg_box = driver.find_element_by_xpath("//*[@id='main']/footer/div[1]/div[2]/div/div[2]")
        msg_box.send_keys(msg) # To send message
        button = driver.find_element_by_xpath("//*[@id='main']/footer/div[1]/div[3]/button")
        button.click() # click send button
    if filepath != "":
        attachment_box = driver.find_element_by_xpath('//div[@title = "Attach"]')
        attachment_box.click() # click attachment icon button
        image_box = driver.find_element_by_xpath(
            '//input[@accept="image/*,video/mp4,video/3gpp,video/quicktime"]')
        image_box.send_keys(filepath) # To send filepath
        sleep(3) # use to set delay time of 3 sec. It will first find the image box,
        send_button = driver.find_element_by_xpath('//span[@data-testid="send"]')
        send_button.click() # click send button
if name != "":
    whatsapp(name, msg, filepath) # parameters are passed at run time using sys.argv
    if msg != "" and filepath == "":
        print("Only message sent successfully")
    elif msg == "" and filepath != "":
        print("Only attachment sent successfully")
    elif msg == "" and filepath == "":
        print("Both message and attachment not sent")
    else:
        print("Both message and attachment sent successfully")
else:
    print("name or group name cannot be empty")

Answers & Solutions

一、EXE无反应的原因与修复方法

你的代码完全可以通过EXE运行,只是打包和运行时没处理好几个关键细节,导致程序静默失败。下面是常见问题的排查和解决步骤:

1. Firefox驱动未被正确打包

Selenium需要geckodriver.exe才能启动Firefox,如果你打包时没把驱动包含进去,exe会因找不到驱动直接崩溃。

  • 修复方案:
    • 把geckodriver.exe放到Python脚本同一目录下。
    • 用pyinstaller打包时,通过--add-data参数将驱动嵌入:
      pyinstaller --onefile --add-data "geckodriver.exe;." your_script.py
      
    • 或者在代码里动态获取驱动路径(适配打包后的临时目录):
      import os
      import sys
      # 获取打包后的临时运行目录,未打包时取脚本所在目录
      base_path = getattr(sys, '_MEIPASS', os.path.dirname(os.path.abspath(__file__)))
      driver_path = os.path.join(base_path, 'geckodriver.exe')
      driver = webdriver.Firefox(executable_path=driver_path)
      

2. 控制台被隐藏,看不到错误信息

如果用--windowed参数打包,程序的控制台会被隐藏,代码中的报错(比如参数缺失、驱动找不到)你完全看不到,误以为程序没反应。

  • 修复方案:
    • 先不带--windowed参数打包:
      pyinstaller --onefile your_script.py
      
    • 从命令行运行exe,这样就能看到所有报错信息,快速定位问题。

3. 缺少运行参数导致崩溃

你的代码一开始就直接读取sys.argv[1]、sys.argv[2]、sys.argv[3],如果双击exe不传递任何参数,会直接抛出IndexError并退出,你自然看不到任何反应。

  • 修复方案:
    • 先从命令行传递参数测试:
      your_script.exe "Contact Name" "Hello World" "C:\path\to\image.jpg"
      
    • 在代码开头添加参数检查,避免崩溃并给出提示:
      if len(sys.argv) < 4:
          print("Usage: your_script.exe <contact_name> <message> <file_path>")
          print("Leave message/file_path empty by passing empty quotes if needed")
          input("Press Enter to exit...")
          sys.exit(1)
      name = sys.argv[1]
      msg = sys.argv[2]
      filepath = sys.argv[3]
      

4. Selenium与Firefox版本不兼容

geckodriver的版本必须和你本地安装的Firefox版本匹配,版本不兼容会导致驱动无法启动浏览器。

  • 修复方案:
    • 查看Firefox版本(帮助→关于Firefox),下载对应版本的geckodriver。

二、给EXE传递参数的两种常用方式

你的代码已经用sys.argv实现了参数传递,这里再明确两种实用的操作方式:

1. 命令行直接传递

打开命令提示符,输入exe路径,后面跟参数即可。如果参数包含空格,用引号包裹:

# 发送消息+文件
your_script.exe "Team Group" "Meeting at 3 PM!" "D:\docs\meeting_notes.pdf"

# 只发消息,文件路径留空
your_script.exe "Mom" "Good morning!" ""

# 只发文件,消息留空
your_script.exe "John Doe" "" "C:\photos\vacation.jpg"

2. 快捷方式传递参数

不想每次打开命令行?可以给exe创建带参数的快捷方式:

  • 右键exe→创建快捷方式
  • 右键快捷方式→属性→在「目标」栏的exe路径后添加参数,示例:
    "C:\dist\your_script.exe" "Dad" "Call me later" ""
    
  • 点击确定,双击快捷方式就能直接运行带参数的exe。

三、额外优化建议

  • 把input('Enter anything after scanning QR code')改成更清晰的提示:input('Press Enter after scanning the WhatsApp QR code...')
  • 添加元素等待逻辑,避免页面加载慢导致找不到元素:
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.support import expected_conditions as EC
    from selenium.webdriver.common.by import By
    
    # 等待联系人元素加载完成,最多等10秒
    user = WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.XPATH, '//span[@title = "{}"]'.format(name)))
    )
    user.click()
    

内容的提问来源于stack exchange,提问作者Ankur Bhalla

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 13:22:51