在导入mechanize时,Python3出现错误
我在用python3导入mechanize的时候遇到了一个错误。
我刚刚在我的虚拟环境中安装了mechanize,而这个环境里有python3。
$ which python3
/Users/myname/.virtualenvs/python3/bin/python3
$ pip freeze
mechanize==0.2.5
但是,当我在我的python代码中尝试导入mechanize时,就出现了这个错误。
import mechanize
---------------------------------------------------------------------------
ImportError Traceback (most recent call last)
<ipython-input-1-6b82e40e2c8e> in <module>()
----> 1 import mechanize
/Users/myname/.virtualenvs/python3/lib/python3.3/site-packages/mechanize/__init__.py in <module>()
117 import sys
118
--> 119 from _version import __version__
120
121 # high-level stateful browser-style interface
ImportError: No module named '_version'
有没有人知道怎么解决这个问题?
我刚开始学习python,最近一直在研究如何编程。
谢谢大家的帮助!
更新
我已经安装了适用于python3的mechanize。现在,我又遇到了一个新的错误。
In [1]: import mechanize
---------------------------------------------------------------------------
ImportError Traceback (most recent call last)
<ipython-input-1-6b82e40e2c8e> in <module>()
----> 1 import mechanize
/Users/myname/.virtualenvs/python3/lib/python3.3/site-packages/mechanize-0.2.6.dev_20140305-py3.3.egg/mechanize/__init__.py in <module>()
120
121 # high-level stateful browser-style interface
--> 122 from ._mechanize import \
123 Browser, History, \
124 BrowserStateError, LinkNotFoundError, FormNotFoundError
/Users/myname/.virtualenvs/python3/lib/python3.3/site-packages/mechanize-0.2.6.dev_20140305-py3.3.egg/mechanize/_mechanize.py in <module>()
/Users/myname/.virtualenvs/python3/lib/python3.3/site-packages/mechanize-0.2.6.dev_20140305-py3.3.egg/mechanize/_html.py in <module>()
ImportError: cannot import name _sgmllib_copy
我检查了一下我在工作虚拟环境中安装的内容,发现了一些警告。
$ pip freeze
cssselect==0.9.1
httplib2==0.8
ipython==1.1.0
lxml==3.2.4
## FIXME: could not find svn URL in dependency_links for this package:
mechanize==0.2.6.dev-20140305
pyquery==1.2.8
Warning: cannot find svn location for mechanize==0.2.6.dev-20140305
3 个回答
我觉得你可能安装了Python 2版本的mechanize,而新的Python 3的导入方式让旧的Python 2代码出现了问题。经过简单搜索,发现mechanize在Python 3上的支持还不是很好。不过,我找到一个Python 3的分支。
你可以试着从我提供的源代码手动安装。下载完源代码后,记得切换到mechanize的目录。然后在终端输入$python3 setup.py install
来进行安装。
这个模块叫做MechanicalSoup,它把Mechanical和BeautifulSoup这两个库合并在了一起,可以在Python 2.6到3.4的版本中使用。
在命令提示符中安装MechanicalSoup:
pip install MechanicalSoup
然后在Python中导入它,
import mechanicalsoup # Don’t forget to import the new module
很遗憾,mechanize这个库不支持Python 3。你可以在这里查看相关信息:http://wwwsearch.sourceforge.net/mechanize/faq.html
它只支持Python 2.4、2.5、2.6或2.7版本。Python 3还不支持。
如果你想对此问题发表看法,可以去这里留言:https://github.com/jjlee/mechanize/issues/96
更新:我自己写了一个自动化的库,叫MechanicalSoup。它是兼容Python 3的,链接在这里:https://github.com/hickford/MechanicalSoup