首页 > 解决方案 > 用python下载图像

问题描述

嗨,我想在此链接中下载图像,但无法打开创建的图像。这是输出文件 在此处输入图像描述 我该如何解决这个问题?这是代码:

from requests.models import Response
import requests

url = 'https://beta.mangaeden.com/it/it-manga/jojo-no-kimyou-na-bouken---jojorion/1/1'
r = requests.get(url)
soup = BeautifulSoup(r.content, 'html.parser')
immagine = soup.find(id='mainImg')
src = str(immagine.get('src'))
link_immagine = "https:"+src
print(link_immagine)
'''download imagege'''
response = requests.get(link_immagine)
f = open("C:\\Users\\chris\\Desktop\\image.jpg", "wb")
f.write(response.content)
f.close()
print('download successfull')

标签: pythonhtmlweb

解决方案


该网站似乎403 Forbidden根据您的用户代理返回错误。如果您使用浏览器的用户代理请求图像,它应该可以工作,例如:

response = requests.get(link_immagine, headers={
        'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0 Safari/537.36'
})

推荐阅读