403在Python中请求图像URL时-在本地工作,但在PythonAnywhere上不工作



我正试图使用Python编写一个twitter bot,它只按时间表推送图像,并从URL数组中随机选择一个。我在imgbb.com上托管这些图片,并使用tweepy推特。

我的代码在本地机器上从终端运行时可以工作,但我现在正试图通过在Python Anywhere上运行它来部署它。在这里,我在尝试获取图像时收到了一个403请求。

获取图像的方法:

def tweet_image(url, message):
filename = 'temp.jpg'
request = requests.get(url, stream=True)
if request.status_code == 200:
with open(filename, 'wb') as image:
for chunk in request:
image.write(chunk)
api.update_with_media(filename, status=message)
os.remove(filename)
else:
print("Unable to download image")

返回错误:

File "/home/user/.virtualenvs/my-virtualenv/lib/python3.6/site-packages/urllib3/connectionpool.py", line 727, in urlopen
method, url, error=e, _pool=self, _stacktrace=sys.exc_info()[2]
File "/home/user/.virtualenvs/my-virtualenv/lib/python3.6/site-packages/urllib3/util/retry.py", line 439, in increment
raise MaxRetryError(_pool, url, error or ResponseError(cause))
urllib3.exceptions.MaxRetryError: HTTPSConnectionPool(host='i.ibb.co', port=443): Max retries exceeded with url: /4gJLdfw/images-12.jpg (Caused by ProxyError('Cannot connect to proxy.', OSError('Tunnel connect
ion failed: 403 Forbidden',)))

我是否需要设置某种类型的用户代理或请求头才能使GET成功?我对python完全陌生。

您可能在PythonAnywhere上有一个免费帐户,因此访问外部世界的权限有限。您可以在此处查看白名单域。我看到i.ibb.co重定向到imgbb.com,它有一个白名单api,所以也许你应该尝试那个域。

相关内容

最新更新