Python:如何使用urllib2访问https
怪我咯
怪我咯 2017-04-17 13:57:15
[Python讨论组]

想要访问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

怪我咯
怪我咯

走同样的路,发现不同的人生

全部回复(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更方便一些~

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号