Python:从URL下载图像但出现HTTP错误403

时间:2020-09-06 11:39:41

标签: python web web-scraping request

我正在尝试下载此图像: https://bu3.mkklcdnbuv1.com/mangakakalot/m2/mother_im_sorry/chapter_5_chapter_5/2.jpg

我尝试过:Set Headers = {'User-agent':'Mozilla / 5.0'}

我收到的代码仍然是403。

有人可以建议我克服这种情况吗?

我的代码:

import requests
import shutil

r = requests.get('https://bu3.mkklcdnbuv1.com/mangakakalot/m2/mother_im_sorry/chapter_5_chapter_5/2.jpg',stream=True, headers={'User-agent': 'Mozilla/5.0'})
print (r.status_code)
if r.status_code == 200:
    with open("img.jgp", 'wb') as f:
        r.raw.decode_content = True
        shutil.copyfileobj(r.raw, f)

1 个答案:

答案 0 :(得分:1)

您需要在代码中设置referer标头,例如:

import requests

with requests.Session() as session:
    resp_2 = session.get("https://bu3.mkklcdnbuv1.com/mangakakalot/m2/mother_im_sorry/chapter_5_chapter_5/2.jpg", headers={"referer":"https://mangakakalot.com/chapter/ro920198/chapter_5"})
    with open("xx.jpg","wb") as f:
        f.write(resp_2.content)