为了账号安全,请及时绑定邮箱和手机立即绑定

如何使用 pyinstaller 将 chromedriver.exe 与在

如何使用 pyinstaller 将 chromedriver.exe 与在

慕仙森 2023-08-15 17:04:49
据我所知,将chromedriver.exe与在 selenium webdriver 上运行的 python 脚本合并或添加。这是我的代码(python):# importing packages / modulesimport osimport service  # This module cannot be installed as it asks for Microsoft Visual C++ 14 to be isntalled on pcfrom selenium import webdriverfrom selenium.webdriver.chrome.options import Options# Defining required functions that needs to be used again and againdef 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"
查看完整描述

1 回答

?
蝴蝶不菲

TA贡献1810条经验 获得超4个赞

我们需要牢记以下两件事:


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 os

import sys


def 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


查看完整回答
反对 回复 2023-08-15
  • 1 回答
  • 0 关注
  • 101 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信