将Python脚本打包exe程序

目录

 

1.安装 PyInstaller库

2.打包

3.打包包含 selenium库 的脚本时遇到的问题

3.1 打包完成运行exe文件报错

3.1.1 No such file or directory: '\\selenium\webdriver\remote\getAttribute.js'

3.1.2 No such file or directory: 'exe文件目录\getAttribute.js'

3.1.3 Module ‘puwintypes’ isn’t in frozen sys.pat

3.1.4 TypeError: an integer is required (got type bytes)

3.1.5 运行时会出现黑窗口,没有隐藏 chromedriver驱动窗口

3.2 selenium 运行关闭后 chromedriver 驱动进程未自动关闭


1.安装 PyInstaller

  • 打包的exe程序不能跨平台使用,如果需要在不同平台使用,就要在相应平台上进行打包。

pip install Pyinstaller

2.打包

  • 将 自定义图标(.ioc) 和 py文件 放在同一个路径下。

  • 终端 cd 到该路径下。

    pyinstaller -F -i 图标.ico py.py
    # 参数
    # -F:生成单个可执行文件,包括依赖也在里面
    # -D:生成一个文件夹,文件夹包括可执行文件和依赖文件
    # -w:使用windows子系统执行,不会打开命令行(只对windows有效)
    # -i:可执行文件的图标
    # .ico:图标
    # .py:python脚本
  • 最后输出 successfully 表示打包成功了。

  • 注意:

    • 路径最好都是英文,不能出现空格和英文句号(.) 。

    • 源文件必须是 UTF-8 编码,暂不支持其他编码类型。

    • 脚本中能够 from xxx import yyy 导入就尽量不要 import xxx ,这样可以减少打包后的体积。


3.打包包含 selenium库 的脚本时遇到的问题

3.1 打包完成运行exe文件报错

        3.1.1 No such file or directory: '\\selenium\webdriver\remote\getAttribute.js'

# 打开 \\Python*\Lib\site-packages\selenium\webdriver\remote\webelement.py

# 将
getAttribute_js = pkgutil.get_data(__pak, 'getAttribute.js').decode('utf8')
isDisplayed_js = pkgutil.get_data(__pak, 'isDisplayed.js').decode('utf8')

# 修改为:
import sys
frozen = getattr(sys, 'frozen', '')
if not frozen:
    getAttribute_js = pkgutil.get_data(__package__, 'getAttribute.js').decode('utf8')
    isDisplayed_js = pkgutil.get_data(__package__, 'isDisplayed.js').decode('utf8')
else:
    approot = os.path.dirname(sys.executable)
    getAttribute_js = open(os.path.join(approot, 'getAttribute.js'), 'rb').read().decode('utf8')
    isDisplayed_js = open(os.path.join(approot, 'isDisplayed.js'), 'rb').read().decode('utf8')

        3.1.2 No such file or directory: 'exe文件目录\getAttribute.js'

# 将 \\selenium\\webdriver\\remote 下面的两个js文件复制到exe文件目录下
getAttribute.js
isDisplayed.js

        3.1.3 Module ‘puwintypes’ isn’t in frozen sys.pat

# pip 默认安装最新的 pyinstaller
# 安装pyinstaller早期版本,如:3.4
pip install pyinstaller==3.4

        3.1.4 TypeError: an integer is required (got type bytes)

pip install https://github.com/pyinstaller/pyinstaller/archive/develop.tar.gz

        3.1.5 运行时会出现黑窗口,没有隐藏 chromedriver驱动窗口

  • 修改 selenium 的文件:\\python*\Lib\site-packages\selenium\webdriver\common\service.py
  • service.py 文件的第76行左右添加:creationflags=134217728


3.2 selenium 运行关闭后 chromedriver 驱动进程未自动关闭

from selenium.webdriver.chrome.service import Service

driver_service = Service('chromedriver.exe')  # 驱动路径
driver_service.command_line_args()
driver_service.start()
 
driver = webdriver.Chrome()
driver.get("http://www.baidu.com")

driver.quit()	#关闭所关联的所有窗口
driver_service.stop()	# 退出驱动进程
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值