使用 python 次请求下载图像

Download image with python requests

我是 python 的新手。我必须从网上下载一些图像并将其保存到我的本地文件系统。我注意到响应内容不包含任何图像数据。 问题只发生在这个特定的 url 上,对于所有其他图像 url 代码工作正常。

我知道最简单的解决方案就是使用另一个 url 但我仍然想问问是否有人遇到过类似的问题。

import requests
    url = 'https://assets.coingecko.com/coins/images/1/large/bitcoin.png'
    filename = "bitcoin.png"

    response = requests.get(url, stream = True)
    response.raw.decode_content = True
    with open(f'images/{filename}', 'wb') as outfile:
       outfile.write(response.content)

首先,查看带有response.text的响应内容,您会看到该网站阻止了您的请求。

Please turn JavaScript on and reload the page.

然后,您可以尝试检查更改请求的 User-Agent 是否可以解决您的问题。

response = requests.get(
    url, 
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.127 Safari/537.36',
    },
    stream = True
)

如果没有,您可能需要使用可以解析 javascript 的内容来获取您的数据,例如 selenium or Puppeteer