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

阅读 32.4k
2 个回答
>>> 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?

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

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题