Python模块导入错误分析

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u011436666/article/details/72862124

分享最近有一次使用Python导模块时的错误:


1、问题产生
最近笔者在练习爬虫的过程中,得知有一个模块叫做builtwith,其中有个parse的方法可以用来检查网站构建的技术类型,于是直接用pip安装了此模块: pip install builtwith。
然后在导入此模块的过程中(import builtwith),始终无法成功,提示信息如下:
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Python35\lib\site-packages\builtwith\__init__.py", line 43
    except Exception, e:
                    ^
SyntaxError: invalid syntax
这时我们可以发现,这个模块是安装成功的,在~\Python35\lib\site-packages\目录下面,并且提示了__init__.py文件的43行有问题。我们可以打开此文件看一看,然而发现这里面用到了urllib2的模块。
    if None in (headers, html):
        try:
            request = urllib2.Request(url, None, {'User-Agent': user_agent})
            if html:
                # already have HTML so just need to make HEAD request for headers
                request.get_method = lambda : 'HEAD'
            response = urllib2.urlopen(request)
            if headers is None:
                headers = response.headers
            if html is None:
                html = response.read()
        except Exception, e:
            print 'Error:', e
            request = None

于是,通过查看文档,可以知道python 3.x中urllib库和urilib2库合并成了urllib库,因此可以基本可以确定此问题就是这样产生的。

2、问题解决

这样的一个问题,最直观的解决方式也许是直接换成Python2.X的版本来运行这个脚本,以达到正确使用builtwith这个我们需要的模块。但是如果我们的项目里面如果又需要使用Python3.X中的模块呢?:)


猜你喜欢

转载自blog.csdn.net/u011436666/article/details/72862124