小白第一次尝试python爬虫,爬下来的图片只有1kb,图片打开显示“image not loaded try to open it externally to fix format problem”办?

图片说明图片说明

通过打印出来的链接打开图片没有问题,下载下来的图片出现了问题

图片在编辑器里打开显示“image not loaded try to open it externally to fix format problem”

你尝试过直接用浏览器打开获取的图片URL吗
如果不能打开,就是有防盗链

应该是防盗链了,使用这样的地址格式试试:

域名/img.html?img=图片地址

第17行的url换成urls试试,现在应该从新解析的域名进了。希望有帮助。

很简单,你在请求上加上headers就可以了,代码如下:

import requests
import re

url = 'https://www.nvshens.org/g/33580/'
response = requests.get(url)
html = response.text
header = {'Referer':url}
urls = re.findall('img src=\'(.*?)\' alt=\'.*?\'',html)
print(urls)
for item in urls:
    filename = item.split('/')[-1]
    res = requests.get(item,allow_redirects=False,headers=header)
    with open(filename,'wb') as f:
        f.write(res.content)