【问题标题】:Issue when downloading image from url with Python使用 Python 从 url 下载图像时出现问题
【发布时间】:2021-09-07 09:45:45
【问题描述】:

我正在尝试使用 requests 和 shutil 库从带有 Python 的 URL 下载图像。我的代码如下:

import requests
import shutil

image_url = "https://www.metmuseum.org/-/media/images/visit/met-fifth-avenue/fifthave_teaser.jpg"

with open("image1.jpg", "wb") as file:
    response = requests.get(image_url, stream=True)
    response.raw.decode_content = True
    shutil.copyfileobj(response.raw, file)
file.close()

此代码适用于我尝试过的大多数其他图片网址(例如:https://tinyjpg.com/images/social/website.jpg)。但是,对于代码中的 image_url,会创建一个 1kb 的文件,并显示“看起来我们不支持这种文件格式”的错误。

我也试过了:

import urllib
urllib.request.urlretrieve(image_url, "image1.jpg)

可以使用 Seleniumwire 执行此操作 - 我使用 driver.requests 获取站点发出的所有请求的列表,然后遍历这些请求,直到获得包含文件类型的 request.response.header ( .jpg)。似乎有两个具有相同 url 的请求(第一个具有内容类型'text/html',第二个具有'image/jpg')。

我想在不加载 WebDriver 的情况下运行它。有什么方法可以使用请求功能下载这样的图像吗?

【问题讨论】:

  • 仅供参考,代码块末尾的file.close() 不是必需的。离开with 块时会自动调用close() 方法,无论是因为已到达块的末尾、引发了异常、已到达returncontinue 之类的控制语句还是任何其他原因.

标签: python selenium web-scraping python-requests urllib


【解决方案1】:

如果您查看response.text,您会发现服务器不喜欢您的请求标头并认为您是机器人:

'<html>\r\n<head>\r\n<META NAME="robots" CONTENT="noindex,nofollow">\r\n<script src="/_Incapsula_Resource?SWJIYLWA=5074a744e2e3d891814e9a2dace20bd4,719d34d31c8e3a6e6fffd425f7e032f3">\r\n</script>\r\n<body>\r\n</body></html>\r\n'

但是,如果您提供正确的 User-Agent 标头,它的响应会发生变化,您可以继续保存文件:

headers = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.106 Safari/537.36'} 

response = requests.get(image_url, stream=True, headers=headers)

with open("image1.jpg", "bw") as file:
    file.write(response.content)

因此,您必须在请求标头中模拟用户代理才能获取此图像。

另外,with 是一个上下文管理器,它已经为你关闭了文件。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-08
    • 2017-08-12
    • 1970-01-01
    • 2013-12-03
    • 2013-01-15
    • 2021-10-22
    • 1970-01-01
    • 2022-01-22
    相关资源
    最近更新 更多