首页 > Python:如何使用urllib2访问https

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


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


>>> import urllib2
>>> f = urllib2.urlopen("https://www.baidu.com/")
>>> buf = f.read()
>>> f.close()
>>> buf
'<html>\r\n<head>\r\n\t<script>\r\n\t\tlocation.replace(location.href.replace("https://","http://"));\r\n\t</script>\r\n</head>\r\n<body>\r\n\t<noscript><meta http-equiv="refresh" content="0;url=http://www.baidu.com/"></noscript>\r\n</body>\r\n</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?

【热门文章】
【热门文章】