我正在尝试从网站下载图像,但是当我从src
标签保存图像时,会得到一个通用图像。
html标记看起来像这样:
<img alt="" data-width="2448" data-height="2448" data-frame="1" data-src="//photo.yupoo.com/huazeltd/4a4591ca/big.jpg" data-origin-src="//photo.yupoo.com/huazeltd/4a4591ca/4a0a44c6.jpg" data-type="photo" data-album-id="62862043" data-videoformats="" data-path="/huazeltd/4a4591ca/4a0a44c6.jpg" class="autocover image__img image__portrait" src="//photo.yupoo.com/huazeltd/4a4591ca/small.jpg">
与该任务相关的我的代码部分如下:
with requests.Session() as c:
c.get('https://huazeltd.x.yupoo.com/albums/62862043?uid=1&referrercate=237897')
res = c.get(f'https://photo.yupoo.com/huazeltd/4a4591ca/small.jpg')
if res.status_code == 200:
with open(f"img/{p.split('/')[-1]}", 'wb') as f:
f.write(res.content)
答案 0 :(得分:1)
我看到一些东西:
1)您没有将c.get的结果分配给res,因此为空
2)在第二个请求之前没有https://
我还没有按原样尝试使用该代码,但是按如下所示进行了修改:
import requests
def get_photos(url):
with requests.Session() as c:
c.get(url)
c.headers.update({'referer': url})
res = c.get('https://photo.yupoo.com/huazeltd/4a4591ca/small.jpg')
if res.status_code == 200:
return res.content
它(现在)返回正确的内容,并通过以下方式进行测试:
url = 'https://huazeltd.x.yupoo.com/albums/62862043?uid=1&referrercate=237897'
with open('photo.jpg', 'wb') as f:
f.write(get_photos(url))
请注意,我现在正在明确设置引荐来源网址。