使用requests下载有限制的图片

2024-04-20 07:10:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图从网站下载一个图像,但是当我从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)

Tags: 标记图像imagesrccomimgdataas
1条回答
网友
1楼 · 发布于 2024-04-20 07:10:19

我看到一些事情:

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))

请注意,我现在明确设置推荐人。你知道吗

相关问题 更多 >