Skip to main content
 首页 » 编程设计

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

2024年12月31日11langtianya

当我尝试使用 aiohttp 下载此链接时,我不断收到 403 错误: http://cfile2.uf.tistory.com/original/996D34465B12921B1AE97C

我想下载 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!) 

请您参考如下方法:

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

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

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