【问题标题】:requests fails to download any image from a certain site although all image there is downloadable?尽管所有图像都可以下载,但请求无法从某个站点下载任何图像?
【发布时间】:2018-08-14 14:26:37
【问题描述】:

这是我用于下载任何图像的代码(除了这个网站 www.pexels.com 之外,它总是可以正常工作)。它实际上下载了图像,但在涉及到该站点时已损坏?我想知道为什么??

url = "https://images.pexels.com/photos/844297/pexels-photo-844297.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940"

response = requests.get(url , stream = True)

file= open("Hello.jpg" , 'wb')

for chunk in response.iter_content(10000):
    file.write(chunk)

file.close()

【问题讨论】:

  • 您的代码 sn-p 对我来说工作得非常好(使用正确的图像创建 Hello.jpg)。
  • @stellasia 我修改了链接,请重试下载这张图片?
  • 如果你不介意切换模块,不妨试试 wget
  • 对不起,现在连 wget 都有问题。它会引发 403 Forbidden 错误。也许这就是导致请求问题的原因?

标签: python python-3.x python-requests


【解决方案1】:

您需要在请求标头中添加user-agent

以下代码有效:

import requests

url = "https://images.pexels.com/photos/844297/pexels-photo-844297.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940"
headers = {"user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36"
}
response = requests.get(url , stream = True, headers=headers)

file= open("Hello.jpg" , 'wb')

for chunk in response.iter_content(10000):
    file.write(chunk)

file.close()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-22
    • 2021-04-03
    • 2011-06-05
    相关资源
    最近更新 更多