【问题标题】:How do I scrape images using Python while ignoring their height & width in the URL?如何在忽略 URL 中的高度和宽度的情况下使用 Python 抓取图像?
【发布时间】:2017-07-30 01:57:03
【问题描述】:

我正在尝试编写 Python 脚本以从 API 下载图像。
API 以如下格式返回图像:

https://stackoverflow.com/media/GetImage?ID=98383838&imageName=03833883.jpg&width=640&height=480`

每张图片换行。我正在尝试使用 urllib,但很难弄清楚如何忽略处理每个 jpg 的宽度/高度,因为我想要完整尺寸的图像而不是 640x480 的。

我一直在测试以下内容:

import urllib
import re

input_file = open('imgurls.txt','r')
x=0
for line in input_file:
    URL= line

    urllib.urlretrieve(URL, str(x) + ".jpg")
    x+=1

我不确定如何解决宽度/高度问题。
我相信我应该使用 rsplit 但不太确定。
如果正在读取的行不是 URL,我还需要移至下一行以避免错误。

【问题讨论】:

    标签: python url urllib


    【解决方案1】:

    cricket_007 的答案对我来说看起来很棒。一种更强大的方法可能是使用urlparse 分解 URL,删除不需要的查询参数并重新构建它:

    import urlparse
    url = 'https://stackoverflow.com/media/GetImage?ID=98383838&imageName=03833883.jpg&width=640&height=480'
    parsed = urlparse.urlparse(url)
    query = parsed.query
    parsed_query = urlparse.parse_qs(query)
    parsed_query.pop('width', None)
    parsed_query.pop('height', None)
    result = urlparse.urlunparse((parsed.scheme, parsed.netloc, parsed.path, parsed.params, urllib.urlencode(parsed_query, True), parsed.fragment))
    

    【讨论】:

      【解决方案2】:

      您可以从 URL 中分离出最后两个查询参数,然后重新加入 URL。

      url = 'https://stackoverflow.com/media/GetImage?ID=98383838&imageName=03833883.jpg&width=640&height=480'
      full_img_url = '&'.join(url.split('&')[:-2])
      
      # 'https://stackoverflow.com/media/GetImage?ID=98383838&imageName=03833883.jpg'
      

      这假设宽度和高度总是最后的。

      【讨论】:

        猜你喜欢
        • 2014-09-13
        • 2016-10-09
        • 1970-01-01
        • 1970-01-01
        • 2022-11-22
        • 2010-12-16
        • 2011-03-21
        • 2012-06-25
        • 1970-01-01
        相关资源
        最近更新 更多