报错一
用 python + selenium 做 web 自动化测试时,为了方便在别的电脑上运行,所以用 pyinstaller 生成 exe 可执行文件,但是生成后无法执行,报错信息在下面。
# 打包成 exe
pyinstaller -D filename.py
python selenium 调用代码
from selenium import webdriver
driver=webdriver.Chrome()
...
报错信息如下
Traceback (most recent call last):
File "site-packages\selenium\webdriver\common\service.py", line 72, in start
File "subprocess.py", line 854, in __init__
File "subprocess.py", line 1307, in _execute_child
FileNotFoundError: [WinError 2] 系统找不到指定的文件。
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "test_baidu.py", line 16, in <module>
File "base_page.py", line 5, in __init__
File "driver.py", line 5, in get_driver
File "site-packages\selenium\webdriver\chrome\webdriver.py", line 73, in __init__
File "site-packages\selenium\webdriver\common\service.py", line 81, 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
[2884] Failed to execute script test_baidu
解决方法
1、把 webdriver 驱动 chromedriver.exe 放到 C:\Program Files (x86)\Google\Chrome\Application 下面
2、把 C:\Program Files (x86)\Google\Chrome\Application 加入 PATH 环境变量中
报错二
打包的 exe 可执行文件出现闪退
解决方法
# 代码段
...
# 在结尾处加上
input()
报错三
报错信息如下,提示模块没有找到
Traceback (most recent call last):
File "run_test.py", line 1, in <module>
File "c:\python\lib\site-packages\PyInstaller\loader\pyimod03_importers.py", line 621, in exec_module
exec(bytecode, module.__dict__)
File "model\myunit.py", line 2, in <module>
ModuleNotFoundError: No module named 'driver'
[23808] Failed to execute script run_test
解决方法
打包时需要将模块路径进行打包,本例 driver 模块路径是 E:\Python_script\auto_test\website\test_case\model,多个路径用分号 ;分隔
pyinstaller run_test.py -p E:\Python_script\auto_test\website\test_case\model
注意点,打包时如果存在多个目录,打包的 *.py 文件也刚好在一个目录内,一定要切换到上层目录打包,不然也会提示模块没找到
打包前的目录树
E:.
├─hr_test
│ │ run_hr.py
│ │
│ ├─model
│ │ base_cls.py
│ │ browser_cls.py
│ │ unit_cls.py
│ │
│ ├─page_object
│ │ add_employee.py
│ │ add_other.py
│ │ hr_login.py
│ │
│ ├─test_case
│ │ │ test_hr.py
│ │ │
│ │ └─__pycache__
│ │ test_hr.cpython-38.pyc
│ │
│ └─test_report
│ 20200121_104709.html
│
上例存在多级目录
Pyinstaller 打包方法
# 先切换到 hr_test 目录
# 这里如果是在 test_case 目录打包,将提示模块不存在
E:\Python_script\ui_test\hr_test>
# 打包,加入路径
pyinstaller test_case/test_hr.py -p E:\Python_script\ui_test\hr_test\model;E:\Python_script\ui_test\hr_test\page_object;E:\Python_script\ui_test\hr_test\test_case
打包后生成的目录树,生成的 build,dist 目录 在根目录 hr_test 下
E:.
├─hr_test
│ │ run_hr.py
│ │ test_hr.spec
│ │
│ ├─build
│ ├─dist # Exe 文件目录
│ ├─model
│ │ base_cls.py
│ │ browser_cls.py
│ │ unit_cls.py
│ │
│ ├─page_object
│ │ add_employee.py
│ │ add_other.py
│ │ hr_login.py
│ │
│ ├─test_case
│ │ test_hr.py
│ │
│ └─test_report
│ 20200121_104709.html
│