【问题标题】:Unable to access Tastekid’s API. It says Error: 403 (Request forbidden)无法访问 Tastekid 的 API。它说错误:403(请求被禁止)
【发布时间】:2015-05-14 06:36:16
【问题描述】:

我无法运行代码来读取 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'

【问题讨论】:

    标签: python json api


    【解决方案1】:

    在向 url 发出请求之前,您需要添加正确的headers

    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 键,以便告诉服务器我们正在从浏览器而不是程序发出请求

    测试

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

    【讨论】:

    • 非常感谢您的更新。但是,如果我必须从程序而不是浏览器发出请求,那么还有其他方法吗?
    • 我所做的更改仅在程序中。将发布整个代码供您参考
    • 这是解决我们问题的好方法。在进行 API 调用时,您不必假装自己是浏览器。我刚刚在 CloudFlare 中添加了一个页面规则来禁用 API URL 的“浏览器完整性检查”,因此不再需要这样做。 (这里是 TasteKid 创始人)
    猜你喜欢
    • 2017-01-04
    • 2021-06-06
    • 2012-06-02
    • 2016-05-16
    • 2020-05-19
    • 2015-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多