简体   繁体   English

使用 python 请求下载图像

[英]Download image with python requests

I'm new to python.我是 python 新手。 I have to download some images from the web and save it to my local file system.我必须从网上下载一些图像并将其保存到我的本地文件系统中。 I've noticed that the response content does not contain any image data.我注意到响应内容不包含任何图像数据。 The problem only occurs with this specific url, with every other image url the code works fine.问题仅出现在这个特定的 url 上,对于每个其他图像 url,代码都可以正常工作。

I know the easiest solution would be just use another url but still i'd like to ask if someone had a similar problem.我知道最简单的解决方案就是使用另一个网址,但我仍然想问是否有人有类似的问题。

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)

First, look at the content of the response with response.text , you'll see the website blocked your request.首先,使用response.text查看响应的内容,您会看到网站阻止了您的请求。

Please turn JavaScript on and reload the page.请打开 JavaScript 并重新加载页面。

Then, you can try to check if changing the User-Agent of your request fixes your issue.然后,您可以尝试检查更改请求的用户代理是否可以解决您的问题。

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
)

If it doesn't, you may need to get your data with something which can parse javascript like selenium or Puppeteer .如果没有,您可能需要使用可以解析 javascript 的东西来获取数据,例如seleniumPuppeteer

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM