2015-05-14 75 views
0

我无法运行代码来读取Tastekid的API(python),它说错误:403(请求禁止)但是我可以访问相同的浏览器中的URL。 对钥匙也一样。无法访问Tastekid的API。它说错误:403(请求禁止)

请找到下面的查询

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' 

回答

1

您需要发出请求的url

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) 

这里头内的User-Agent键被设定为前加适量headers告诉服务器我们正在从浏览器而不是程序发出请求

测试

  • 文件名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 
    
+0

非常感谢您的更新。但是,如果我必须从程序而不是浏览器发出请求,那么还有其他方法吗? – vedami

+0

我所做的更改仅限于程序中。将张贴整个代码供您参考 – nu11p01n73R

+0

这是解决我们问题的一个很好的解决方法。在进行API调用时,您不应该假装成为浏览器。我只是在CloudFlare中添加了一个页面规则来禁用API URL的“浏览器完整性检查”,所以不必再这样做。 (TasteKid创始人) –