首页 > 解决方案 > Python Pyinstaller GUI Tkinter Selenium

问题描述

在我在这里问之前,我不知道如何创建一个可执行的 python 程序。谢天谢地,我收到了一个快速的答复,并且能够将我的脚本转换为可执行程序。可执行文件完美运行,但仅在我的计算机上运行。这是我收到的两个错误,我觉得我需要修改脚本才能找到 chrome 驱动程序我不确定 Pyinstaller 将所有内容保存在哪里。

Exception in Tkinter callback
Traceback (most recent call last):
File "site-packages\selenium\webdriver\common\service.py", line 76, in start
File "subprocess.py", line 775, in __init__
File "subprocess.py", line 1178, in _execute_child
FileNotFoundError: [WinError 2] The system cannot find the file specified

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "tkinter\__init__.py", line 1705, in __call__
File "MarijuanaDoctors.py", line 25, in search
File "site-packages\selenium\webdriver\chrome\webdriver.py", line 68, in __init__
File "site-packages\selenium\webdriver\common\service.py", line 83, in start
selenium.common.exceptions.WebDriverException: Message: 'chromedriver' 
executable needs to be in PATH. Please see 
https://sites.google.com/a/chromium.org/chromedriver/home

标签: pythonseleniumtkinterpyinstaller

解决方案


您可以使用 Pyinstaller 将“chromedriver.exe”与脚本捆绑在一起,如下所示:

pyinstaller --add-binary="localpathtochromedriver;." myscript.py

这会将“chromedriver.exe”文件复制到与您的主 .exe 相同的文件夹中(或者在 pyinstaller 的单个文件选项的情况下,此填充将在使用 exe 程序时提取到临时文件夹中)。

在您的脚本中,您可以检查您是正常运行脚本还是从捆绑(exe 文件)模式运行,并相应地选择 chromedriver.exe 的路径。(脚本中的这种更改对于 pyinstaller 的单个文件/文件夹捆绑选项很常见)

import sys
if getattr(sys, 'frozen', False ):
    #Running from exe, so the path to exe is saved in sys._MEIPASS
    chrome_driver = os.path.join(sys._MEIPASS, "chromedriver.exe")
else:
    chrome_driver = 'localpathtochromedriver.exe'
driver = webdriver.Chrome(executable_path=chrome_driver)

您可以在此处的文档中阅读有关此内容的信息。

限制:您的 .exe 用户应在其系统上安装 Chrome,并且 Chrome 版本应与捆绑的 chromedriver 一起使用。


推荐阅读