当我尝试使用aiohttp:http://cfile2.uf.tistory.com/original/996D34465B12921B1AE97C下载这个链接时,我一直收到403个错误。
我想下载http://cfile2.uf.tistory.com/original/996D34465B12921B1AE97C.jpg,但我无法下载。我甚至试图添加引用,但仍然会出现同样的错误。
这是我的代码:
async with aiohttp.ClientSession(headers={'Referer': 'https://tistory.com'}) as cs:
async with cs.get('http://cfile2.uf.tistory.com/original/996D34465B12921B1AE97C.jpg') as r:
if r.status == 200:
img = await r.read()
with open('C:/xxxx/xxxx/xxxx/xxxx/Image/' + 'test.jpg', 'wb') as f:
f.write(img)
print('Downloaded!)发布于 2018-12-17 16:45:37
如果您请求http://cfile2.uf.tistory.com/original/996D34465B12921B1AE97C.jpg,您将得到一个403个禁忌,它可以从响应头中看到。403禁忌是HTTP服务器发送给客户端的HTTP状态代码,以表明服务器理解请求,但不遵守请求。这在这里是有意义的,因为HTTP服务器可能没有为您请求的扩展提供服务。
但是,您可以只请求http://cfile2.uf.tistory.com/original/996D34465B12921B1AE97C (它在响应头中返回200个OK ),并将其写入一个新的.jpg文件:
from requests import get
from requests import RequestException
from os.path import basename
from os.path import join
url = 'http://cfile2.uf.tistory.com/original/996D34465B12921B1AE97C'
jpg_file = basename(url) + '.jpg'
path = join('C:/xxxx/xxxx/xxxx/xxxx/Image/', jpg_file)
try:
r = get(url, stream=True)
r.raise_for_status()
with open(jpg_file, mode='wb') as f:
for chunk in r.iter_content(chunk_size=1024):
if chunk:
f.write(chunk)
except RequestException as err:
print(err)上面的代码还以块的形式下载图像,以防文件非常大。
发布于 2018-12-17 16:42:20
您不能请求这个资源,因为服务器在某种程度上限制了对它的访问。实际上,您收到的响应是一个http错误代码,为403。
如果您在网上搜索,您可以找到一些详细信息:
HTTP 403是由HTTP服务器向客户端传递的标准HTTP状态代码,用于指示服务器理解请求,但由于与授权有关的某些原因而不履行请求。有许多子状态错误代码为使用403状态代码响应提供了更具体的原因。
尝试查看子状态,看看原因是什么,从那里您可以找到一些方法来使它工作。
备注
就像@Dalvenjia说的,如果删除文件上的扩展名,请求似乎运行良好。
https://stackoverflow.com/questions/53819296
复制相似问题