首页 > 解决方案 > 通过请求python仅在heroku远程机器上访问被拒绝错误

问题描述

我面临这个问题,当我从本地机器访问 url 的页面源时,它工作正常,但是当我在 heroku 机器上的代码上运行相同的代码时,它显示访问被拒绝。

我曾尝试更改标题(例如添加Referers或更改User-Agent),但这些解决方案都不起作用。

本地机器

~/Development/repos/eater-list  master  python manage.py shell            1 ↵  12051  21:15:32
>>> from accounts.zomato import *
>>> z = ZomatoAPI()
>>> response = z.page_source(url='https://www.zomato.com/ncr/the-immigrant-cafe-khan-market-new-delhi')
>>> response[0:50]
'<!DOCTYPE html>\n<html  lang="en"  prefix="og: http'
>>> response[0:100]
'<!DOCTYPE html>\n<html  lang="en"  prefix="og: http://ogp.me/ns#" >\n<head>\n    <meta charset="utf-8"

远程机器

~ $ python manage.py shell
Python 3.5.7 (default, Jul 17 2019, 15:27:27)
[GCC 7.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from accounts.zomato import *
>>> z = ZomatoAPI()
>>> response = z.page_source(url='https://www.zomato.com/ncr/the-immigrant-cafe-khan-market-new-delhi')
>>> response
'<HTML><HEAD>\n<TITLE>Access Denied</TITLE>\n</HEAD><BODY>\n<H1>Access Denied</H1>\n \nYou don\'t have permission to access "http&#58;&#47;&#47;www&#46;zomato&#46;com&#47;ncr&#47;the&#45;immigrant&#45;cafe&#45;khan&#45;market&#45;new&#45;delhi" on this server.<P>\nReference&#32;&#35;18&#46;56273017&#46;1572225939&#46;46ec5af\n</BODY>\n</HTML>\n'
>>>

ZOMATO API 代码

标头或请求版本没有变化。

class ZomatoAPI:
    def __init__(self):
        self.user_key = api_key
        self.headers = {
            'Accept': 'application/json',
            'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) '
                          'Chrome/77.0.3865.90 Safari/537.36',
            'user-key': self.user_key}

    def page_source(self, url):
        fng = requests.session()
        page_source = fng.get(
            url, headers=self.headers).content.decode("utf-8")
        return page_source

将不胜感激一些建议。

标签: pythondjangoherokupython-requestszomato-api

解决方案


检查响应 HTTP 状态代码。可能是 Heroku 的 IP 被 Zomato 禁止了。这比人们想象的更普遍——像 Cloudflare 这样的服务很多时候会将常见的 IP 放在“禁止列表”中。

是您应该寻找的有关 HTTP 状态代码的内容,以便为您提供更多上下文。


推荐阅读