【问题标题】:Saving an image from a URL that does not end with image extension从不以图像扩展名结尾的 URL 保存图像
【发布时间】:2021-02-15 18:52:25
【问题描述】:

我是 python 初学者。我有一个包含数千个 URL 的数据集列。我想将图像及其扩展名保存在每个 URL 中。我对以图像扩展名结尾的网址没有问题,例如 https://web.archive.org/web/20170628093753im_/http://politicot.com/wp-content/uploads/2016/12/Sean- Spicer.jpg.(带有 urllib 或请求) 但是对于链接 1=https://nypost.com/wp-content/uploads/sites/2/2017/11/171106-texas-shooter-church-index.jpg?quality=90&strip=all&w=1200 或链接 2=https://i2.wp.com/www.huzlers.com/wp-content/uploads/2017/03/maxresdefault.jpeg?fit=1280%2C720&ssl=1 之类的 URL,我无法保存它们。 我想将图像保存在链接中,如下所示:image1.jpg 和 image2.jpeg。我们应该怎么做? 任何帮助都可能有用。

【问题讨论】:

  • 您可以尝试在 ? 符号上拆分字符串,并将第一个拆分保留为 URL。
  • 请提供您想要反馈的代码示例。

标签: python image python-requests urllib


【解决方案1】:

以下似乎对我有用,试一试:

import requests
urls = ['https://nypost.com/wp-content/uploads/sites/2/2017/11/171106-texas-shooter-church-index.jpg?quality=90&strip=all&w=1200',
        'https://i2.wp.com/www.huzlers.com/wp-content/uploads/2017/03/maxresdefault.jpeg?fit=1280%2C720&ssl=1']

for i, url in enumerate(urls):
    r = requests.get(url)
    filename = 'image{0}.jpg'.format(i+1)

    with open(filename, 'wb') as f:
        f.write(r.content)

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-06-18
  • 2013-12-25
  • 1970-01-01
  • 2012-01-22
  • 1970-01-01
  • 2022-01-04
  • 2021-02-02
相关资源
最近更新 更多