使用aiohttp下载tistory链接时出现403错误

403 error when downloading tistory links with aiohttp

当我尝试使用 aiohttp 下载这个 link 时,我总是收到 403 错误: http://cfile2.uf.tistory.com/original/996D34465B12921B1AE97C

我想下载 http://cfile2.uf.tistory.com/original/996D34465B12921B1AE97C.jpg 但我无法下载。我什至尝试添加 referer,但我仍然遇到同样的错误。

这是我的代码:

        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!)

您无法请求此资源,因为服务器以某种方式限制了对其的访问。事实上,您收到的响应是 403 的 http 错误代码。

如果您在线搜索,您可以找到一些详细信息:

HTTP 403 is a standard HTTP status code communicated to clients by an HTTP server to indicate that the server understood the request, but will not fulfill it for some reason related to authorization. There are a number of sub-status error codes that provide a more specific reason for responding with the 403 status code

尝试查看子状态以查看原因是什么,然后您可以从中找到一些方法使其正常工作。

备注

就像@Dalvenjia 所说的那样,如果您删除文件的扩展名,请求似乎可以正常工作。

如果您请求 http://cfile2.uf.tistory.com/original/996D34465B12921B1AE97C.jpg,您会收到 403 Forbidden,这可以从响应 headers 中看出。 403 Forbidden 是 HTTP 服务器发送给客户端的 HTTP 状态码,表示服务器理解请求,但不会遵从请求。这在这里很有意义,因为 HTTP 服务器可能不提供您请求的扩展。

但是,您可以只请求 http://cfile2.uf.tistory.com/original/996D34465B12921B1AE97C,它会在响应 headers 中返回 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)

以上代码还分块下载图像,以防文件很大。