【问题标题】:Downloading images using requests in Python3在 Python3 中使用请求下载图像
【发布时间】:2019-11-25 01:39:59
【问题描述】:

我需要使用 Python 从 url 下载图像。我正在使用它来这样做:

import requests

with requests.get(url, stream=True) as r:
    with open(img_path, "wb") as f:
        f.write(r.content)

为了让我在浏览器中看到图像,我需要在该网站上登录我的帐户。图片可能是由其他人或我自己发送的。

问题是我能够成功下载一些图像,但对于其他图像,我得到一个身份验证错误,即我没有登录。

在这种情况下,有时它会下载一个内容如下的文件:

{"result":"error","msg":"Not logged in: API authentication or user session required"}

有时,它会下载要求我登录查看图像的网页的 html 文件。

为什么我只在某些情况下收到此错误,而在其他情况下却没有?我应该如何解决它?

【问题讨论】:

  • 使用 HTTPBasicAuth

标签: python web-scraping python-requests


【解决方案1】:

尝试:

import requests

image_url = "https://www.python.org/static/community_logos/python-logo-master-v3-TM.png"
img_data = requests.get(image_url).content
with open('image_name.jpg', 'wb') as handler:
    handler.write(img_data)

注意:

授权

from requests.auth import HTTPBasicAuth
img_data = requests.get('image_url', auth=HTTPBasicAuth('user', 'pass')).content

【讨论】:

  • 感谢您的回复。但是,它不起作用。它给了我“无效的 API 密钥”(我猜这是因为当我尝试手动执行此操作时,即以隐身方式打开链接,然后登录,它会将我重定向到主页,而不是图像所在的页面)。此外,我不能使用它,因为一堆用户将使用这个脚本。我仍然不明白为什么它在某些情况下有效而在其他情况下无效?
【解决方案2】:

您可以使用 response.raw 文件对象,也可以遍历响应。

import requests
import shutil
from requests.auth import HTTPBasicAuth

r = requests.get(url, auth=HTTPBasicAuth('user', 'pass'), stream=True)
if r.status_code == 200:
    with open(path, 'wb') as f:
        r.raw.decode_content = True
        shutil.copyfileobj(r.raw, f)  

【讨论】:

  • 你会为路径放什么?如果你想让它进入你的下载文件夹,你需要把它的路径放在那里吗?
  • @LarissaFord 是的,路径是您要保存该文件的位置。
猜你喜欢
  • 2016-10-11
  • 2012-10-19
  • 1970-01-01
  • 1970-01-01
  • 2022-01-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-13
相关资源
最近更新 更多