如何使用 pyinstaller 将 chromedriver.exe 与在

据我所知,chromedriver.exe与在 selenium webdriver 上运行的 python 脚本合并或添加。

这是我的代码(python):

# importing packages / modules

import os

import service  # This module cannot be installed as it asks for Microsoft Visual C++ 14 to be isntalled on pc


from selenium import webdriver

from selenium.webdriver.chrome.options import Options


# Defining required functions that needs to be used again and again

def init_driver():

    chrome_path = os.path.join(os.path.dirname(__file__), 'selenium','webdriver','chromedriver.exe')

    service = service.Service(chrome_path)  # So, this cannot be used to merge it.

    path = webdriver.Chrome(service, options=Options())


driver = init_driver()

以及 cmd 中给出的命令:


pyinstaller --noconfirm --onefile --console --icon "path/to/icon.ico" --add-binary "path/to/chrome/driver;./driver" "path/to/the/python/pythonscript.py"


慕仙森
浏览 104回答 1
1回答

蝴蝶不菲

我们需要牢记以下两件事:pyinstaller 选项源代码中驱动程序的路径Chromedriver.exe 是一个二进制文件,因此,我们可以使用--add binary我在问题中提到的方式将其添加到 Pyinstaller 中。因此,我们在 cmd 中的 pyinstaller 命令将是这样的:pyinstaller --noconfirm --onefile --console --icon "path/to/icon.ico" --add-binary "path/to/chrome/driver;./driver" "path/to/the/python/pythonscript.py"其次,我们需要以这样的方式修改源代码,使其既不会损害Python控制台中的代码,也不会损害转换后的可执行文件中的代码。因此,我们需要将driver_path代码更改为driver = webdriver.Chrome('path/to/chromedriver.exe', options=Options())像这样的事情import osimport sysdef resource_path(another_way):    try:        usual_way = sys._MEIPASS  # When in .exe, this code is executed, that enters temporary directory that is created automatically during runtime.    except Exception:        usual_way = os.path.dirname(__file__)  # When the code in run from python console, it runs through this exception.    return os.path.join(usual_way, another_way)driver = webdriver.Chrome(resource_path('./driver/chromedriver.exe'), options=Options())我们编写该Exception部分是为了使其能够与 python 控制台一起工作。如果仅以 .exe 格式运行是主要目标,那么我们也可以忽略 Exception 部分。当我们尝试从类中_MEIPASS访问受保护的成员时,此代码会在 python 控制台中抛出警告。除此之外,突出显示sys.pyi的是找不到引用。_MEIPASS
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python