python内置的urllib模块不支持https协议的解决办法

来源:互联网 发布:淘宝哪家的卫衣好 编辑:程序博客网 时间:2024/06/05 18:34

>>> import urllib

>>> urllib.urlopen('http://www.baidu.com')
<addinfourl at 269231456 whose fp = <socket._fileobject object at 0xff98250>>
>>> urllib.urlopen('https://www.baidu.com')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/python27/lib/python2.7/urllib.py", line 86, in urlopen
    return opener.open(url)
  File "/usr/local/python27/lib/python2.7/urllib.py", line 204, in open
    return self.open_unknown(fullurl, data)
  File "/usr/local/python27/lib/python2.7/urllib.py", line 216, in open_unknown
    raise IOError, ('url error', 'unknown url type', type)
IOError: [Errno url error] unknown url type: 'https'

之所以python内置的urllib模块不支持https协议是因为编译安装python之前没有编译安装类似于openssl这样的SSL库,以至于python不支持SSL

1、Centos系统所以安装openssl-devel
sudo yum install openssl-devel


2、第二种方法安装

直接使用这个方法,最直接

安装openssl和openssl-devel


之后重新编译Python
./configure(可选,因为之前已经配置过,按之前的配置来就行了,而且最好按之前的配置配编译安装以免依赖的库需要重新编译安装。)
make
make install

>>> import urllib
>>> urllib.urlopen('https://www.baidu.com')

没有再报同样的错误。

在安装完openssl-devel后重新编译python前也有说需要编辑Modules文件夹内Setup.dist文件的
修改
# Socket module helper for SSL support; you must comment out the other
# socket line above, and possibly edit the SSL variable:
#SSL=/usr/local/ssl
#_ssl _ssl.c \
#        -DUSE_SSL -I$(SSL)/include -I$(SSL)/include/openssl \
#        -L$(SSL)/lib -lssl -lcrypto

 # Socket module helper for SSL support; you must comment out the other
# socket line above, and possibly edit the SSL variable:
SSL=/usr/local/ssl
_ssl _ssl.c \
        -DUSE_SSL -I$(SSL)/include -I$(SSL)/include/openssl \
        -L$(SSL)/lib -lssl -lcrypto

但实际测试下来好像并不需要修改这个文件,编译的时候能自动将SSL库编译进python中。
原创粉丝点击