我无法运行代码来读取Tastekid的API(python),它说错误:403(请求禁止)但是我可以在浏览器中访问相同的URL。 用钥匙也试过了。
请在下面查询
from urllib2 import Request, urlopen, URLError
req = Request('http://www.tastekid.com/api/similar?q=red+hot+chili+peppers%2C+pulp+fiction')
try:
response = urlopen(req)
except URLError as e:
if hasattr(e, 'reason'):
print 'We failed to reach a server.'
print 'Reason: ', e.reason
elif hasattr(e, 'code'):
print 'The server couldn\'t fulfill the request.'
print 'Error code: ', e.code
else:
'everything is fine'
答案 0 :(得分:1)
在向网址
发出请求之前,您需要添加适当的headersheaders = { 'User-Agent' : "Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)" }
req = Request('http://www.tastekid.com/api/similar?q=red+hot+chili+peppers%2C+pulp+fiction', headers = headers)
此处设置标题中的User-Agent
键,以便告诉服务器我们是从浏览器而不是程序发出请求
<强>测试强>
文件名test.py
from urllib2 import Request, urlopen, URLError
#Changes made in the below two line
headers = { 'User-Agent' : 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)' }
req = Request('http://www.tastekid.com/api/similar?q=red+hot+chili+peppers%2C+pulp+fiction', headers = headers)
try:
response = urlopen(req)
except URLError as e:
if hasattr(e, 'reason'):
print 'We failed to reach a server.'
print 'Reason: ', e.reason
elif hasattr(e, 'code'):
print 'The server couldn\'t fulfill the request.'
print 'Error code: ', e.code
else:
print 'everything is fine'
没有标题
$ python test.py
We failed to reach a server.
Reason: Forbidde
带标题
$ python test.py
everything is fine