使用urllib2的Python回溯错误

2024-06-12 05:15:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我真的很困惑,我是Python的新手,我正在编写一个脚本,为Python27上的产品创建一个网站。我尝试使用urllib2来完成这项工作,当我运行脚本时,它会输出多个回溯错误。建议?在

脚本:

import urllib2, zlib, json

url='https://launches.endclothing.com/api/products'
req = urllib2.Request(url)
req.add_header(':host','launches.endclothing.com');req.add_header(':method','GET');req.add_header(':path','/api/products');req.add_header(':scheme','https');req.add_header(':version','HTTP/1.1');req.add_header('accept','application/json, text/plain, */*');req.add_header('accept-encoding','gzip,deflate');req.add_header('accept-language','en-US,en;q=0.8');req.add_header('cache-control','max-age=0');req.add_header('cookie','__/');req.add_header('user-agent','Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/37.0.2062.120 Chrome/37.0.2062.120 Safari/537.36');
resp = urllib2.urlopen(req).read()
resp = zlib.decompress(bytes(bytearray(resp)),15+32)
data = json.loads(resp)
for product in data:
    for attrib in product.keys():
        print str(attrib)+' :: '+ str(product[attrib])
    print '\n'

错误:

^{pr2}$

Tags: https脚本addjsonurl错误urllib2product
1条回答
网友
1楼 · 发布于 2024-06-12 05:15:48

您的请求的SSL配置遇到问题。很抱歉,我不会更正您的代码,因为我们在2016年,您应该使用一个非常好的库:requests

所以它的用法非常简单:

>>> user_agent = 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0) Gecko/20100101 Firefox/40.1'
>>> result = requests.get('https://launches.endclothing.com/api/products', headers={'user-agent': user_agent})
>>> result
<Response [200]>
>>> result.json()
[{u'name': u'Adidas Consortium x HighSnobiety Ultraboost', u'colour': u'Grey', u'id': 30, u'releaseDate': u'2016-04-09T00:01:00+0100', …

您会注意到,我在上一个查询中更改了用户代理以使其正常工作,因为奇怪的是,网站拒绝对requests的API访问:

^{pr2}$

否则,既然你已经尝试了requests并且你的生活已经改变了,你可能还会再次遇到这个问题。正如您可能从互联网上的许多地方读到的,这与SNI and outdated libraries有关,您可能会在试图弄清楚这一点时感到头疼。我最好的建议是升级到Python3,因为这个问题很可能通过安装一个新的python版本和相关的libs来解决。在

高温

相关问题 更多 >