如何解决403在Python中请求图像URL时-在本地工作,但不适用于PythonAnywhere
我正在尝试使用Python编写一个Twitter机器人,该机器人只是按时间表发送图像推特,并从一组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,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上拥有一个免费帐户,因此对外界的访问受到限制。您可以检查列入白名单的域here。我看到
function OnLoad() {
let logFile = Path.join(__dirname,'logs',platformDirs[process.platform],'my.log');
let logElem = document.querySelector('.log');
processLineByLine(logFile,logElem);
}
//
// helpers
//
async function processLineByLine(txtFile,outElement) {
const fileStream = fs.createReadStream(txtFile);
const rl = readline.createInterface({
input: fileStream,crlfDelay: Infinity
});
// Note: we use the crlfDelay option to recognize all instances of CR LF
// ('\r\n') in input.txt as a single line break.
for await (const line of rl) {
// Each line in input.txt will be successively available here as `line`.
console.log(`Line from file: ${line}`);
outElement.innerHTML += line + '<br>';
}
}
重定向到具有列入白名单的api的inline bool OpenLogFile(FILE** ppLogFile) {
TCHAR logPath[MAX_PATH];
DWORD length = GetModuleFileName(NULL,logPath,MAX_PATH);
bool isPathValid = false;
#if (NTDDI_VERSION >= NTDDI_WIN8)
PathCchRemoveFileSpec(logPath,MAX_PATH);
HRESULT resPath = PathCchCombine(logPath,MAX_PATH,TEXT("my.log"));
isPathValid = (resPath == S_OK);
#else
PathRemoveFileSpec(logPath);
LPWSTR resPath = PathCombine(logPath,TEXT("my.log"));
isPathValid = (resPath != NULL)
#endif
if (!isPathValid)
return false;
errno_t res = _wfopen_s(ppLogFile,L"a");
if (res != 0) {
wprintf(TEXT("Error: Failed to open log file: %s"),GetOSErrStr().c_str());
}
return res == 0;
}
,所以也许您应该尝试使用该域。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。