Selenium打包成exe运行出错
很久没写博文了,今天解决了一个其实也不是很复杂的问题,搜了好久的谷歌、百度,发现没怎么找到相关比较好的解决方法,或许是大家都能很轻松的解决这个问题吧,但我还是把我自己的解决方法分享下吧。
最近刚好需要写程序调用Selenium自动化跑一些东西,写好工具后准备打包,发现无限的出错,网上搜了好久也没找到确切答案,那么自己动手吧。
1.Firefox引擎找不到selenium\\webdriver\\firefox\\webdriver_prefs.json文件
如上图所示,提示的是找不到webdriver_prefs.json文件,于是我们进入selenium所安装目录下找到对应文件,放到打包完工具同目录下
(例:C:\Python27\Lib\site-packages\selenium\webdriver\firefox)
运行发现依然出现这个问题,于是我们根据提示打开firefox_profile.py,查看第65行代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
class
FirefoxProfile(
object
):
ANONYMOUS_PROFILE_NAME
=
"WEBDRIVER_ANONYMOUS_PROFILE"
DEFAULT_PREFERENCES
=
None
def
__init__(
self
, profile_directory
=
None
):
"""
Initialises a new instance of a Firefox Profile
:args:
- profile_directory: Directory of profile that you want to use.
This defaults to None and will create a new
directory when object is created.
"""
if
not
FirefoxProfile.DEFAULT_PREFERENCES:
with
open
(os.path.join(os.path.dirname(__file__),
WEBDRIVER_PREFERENCES)) as default_prefs:
FirefoxProfile.DEFAULT_PREFERENCES
=
json.load(default_prefs)
|
我们发现问题所在
1
|
os.path.dirname(__file__)
|
该语句用于获取脚本自身路径,但在打包后就不能这么使用了,于是我们需要对代码进行修改,修改后代码放上
1
2
3
4
5
6
7
8
9
|
if
not
FirefoxProfile.DEFAULT_PREFERENCES:
if
hasattr
(sys,
"frozen"
):
with
open
(os.path.join(os.path.dirname(os.path.abspath(
unicode
(sys.executable, sys.getfilesystemencoding()))),
WEBDRIVER_PREFERENCES)) as default_prefs:
FirefoxProfile.DEFAULT_PREFERENCES
=
json.load(default_prefs)
else
:
with
open
(os.path.join(os.path.dirname(__file__),
WEBDRIVER_PREFERENCES)) as default_prefs:
FirefoxProfile.DEFAULT_PREFERENCES
=
json.load(default_prefs)
|
使用hasattr方法判断程序是否打包,如果打包就使用sys.executable方法获取自身路径
修改完成后我们重新打包,运行发现之前的问题不见了,出现了另一个问题:
2.Firefox引擎找不到selenium\\webdriver\\firefox\\webdriver.xpi文件
如上图所示发现缺少另一个文件webdriver.xpi,同样的拷贝后发现问题依旧,于是我们继续修改代码,查看第260行代码
1
2
3
4
5
6
7
8
9
|
def
_install_extension(
self
, addon, unpack
=
True
):
"""
Installs addon from a filepath, url
or directory of addons in the profile.
- path: url, path to .xpi, or directory of addons
- unpack: whether to unpack unless specified otherwise in the install.rdf
"""
if
addon
=
=
WEBDRIVER_EXT:
addon
=
os.path.join(os.path.dirname(__file__), WEBDRIVER_EXT)
|
同样是打包后路径问题,狠下心我们继续把代码改了
1
2
3
4
5
6
|
if
addon
=
=
WEBDRIVER_EXT:
if
hasattr
(sys,
"frozen"
):
addon
=
os.path.join(os.path.dirname(os.path.abspath(
unicode
(sys.executab le, sys.getfilesystemencoding()))),
WEBDRIVER_EXT)
else
:
addon
=
os.path.join(os.path.dirname(__file__), WEBDRIVER_EXT)
|
最后再打包一次,现在已经能够正常运行了,跑起来吧,跑起来你会赢~
(注:个中代码并不是很难,有不懂的联系下代码上下文,自己理解下吧,或者直接在博文下留言吧,有空我会回复的)