Python:如何使用urllib2访问https

想要访问https网站,获取网页的源代码,如:https://www.baidu.com
源码如下:

f = urllib2.urlopen"https://www.baidu.com/"
buf = f.read
f.close

结果报错:
urllib2.URLError: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed _ssl.c:581>

Python版本:2.7.9
运行平台:Windows

>>> import urllib2
>>> f = urllib2.urlopen"https://www.baidu.com/"
>>> buf = f.read
>>> f.close
>>> buf
<html> <head> <script> location.replacelocation.href.replace"https://","http://"; </script> </head> <body> <noscript><meta http-equiv="refresh" content="0;url=http://www.baidu.com/"></noscript> </body> </html>
>>>

在Mac下运行是正常的,应该是你的环境下不支持SSL,Windows环境需要自行安装

Note HTTPS support is only available if the socket module was compiled with SSL support.

附一下安装方法,希望能对你有帮助:
How to install Python ssl module on Windows?

https 访问,使用pycurl更方便一些~

发表评论

电子邮件地址不会被公开。 必填项已用*标注