python - 尽管所有图像都可下载,但请求无法从某个站点下载任何图像?

标签 python python-3.x python-requests

这是我用来下载任何图像的代码(除了这个网站 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()

最佳答案

您需要将用户代理添加到请求 header 中。

以下代码有效:

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

关于python - 尽管所有图像都可下载,但请求无法从某个站点下载任何图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51843791/

相关文章:

javascript - DropzoneJS XHR 发送选项请求

python - 使用推导式将 Python 字典数组转换为 Python 字典

python - 检查列表的n个成员是否在python中的另一个列表中

python - 递归 Python 神经网络 - Reshape () 错误

python - pandas如何根据df中的其他 bool 列创建 bool 列

python - 如何以最快的速度向我的用户发布 100,000 条独特的消息?

python - 从 Python 使用 POST 发送文件

python - 在等待线程完成时卡住/挂起 tkinter GUI

python - 如何避免多个 `elif` 语句?

python - 请求无法从网页获取文本?