【问题标题】:Curl only save if not 404如果不是 404,则仅卷曲保存
【发布时间】:2012-01-06 10:50:28
【问题描述】:

我正在编写一个 python 程序,用于下载我学校学生的一些照片。

这是我的代码:`

import os
count = 0
max_c = 1000000
while max_c >= count:
    os.system("curl http://www.tjoernegaard.dk/Faelles/ElevFotos/"+str(count)+".jpg > "+str(count)+".jpg")
    count=count+1

`

问题是,如果图像存在于服务器上(不是 404),我只想保存 jpg,并且由于我没有服务器上的所有图像名称,我必须发送所有图像的请求在 0 到 1000000 之间,但并非所有介于 0 到 1000000 之间的图像都存在。所以我只想保存图像,如果它存在于服务器上。我该怎么做(ubuntu)?

提前谢谢你

【问题讨论】:

    标签: python curl download


    【解决方案1】:

    您可以使用“-f”参数静默失败(不输出 HTTP 错误),例如:

    curl -f site.com/file.jpg

    【讨论】:

    • 正是我想要的!
    【解决方案2】:
    import urllib2
    import sys
    
    for i in range(1000000):
      try:
        pic = urllib2.urlopen("http://www.tjoernegaard.dk/Faelles/ElevFotos/"+str(i)+".jpg").read()
        with open(str(i).zfill(7)+".jpg") as f:
          f.write(pic)
        print "SUCCESS "+str(i)
      except KeyboardInterrupt:
        sys.exit(1)
      except urllib2.HTTPError, e:
        print "ERROR("+str(e.code)+") "+str(i)
    

    应该可以,404 会抛出异常

    【讨论】:

    • 呃,不要像这样使用+,它不是pythonic。使用%s等。
    • 我发现 % 语法很麻烦,并且 "".format() 并没有让它变得更好。因此,我什至懒得在小脚本中遵守上帝赋予的蟒蛇法则。
    • 是的,不鼓励使用“+”语法,主要是因为性能和安全问题;如果两者都不是问题,谁在乎。
    • 代码 sn-ps 不需要被 linted。说真的,这只是概念验证而不是原型,请降低标准。
    【解决方案3】:

    我建议使用 python 提供的urllib 库来满足您的目的。

    count = 0
    max_c = 1000000
    while max_c >= count:
        resp = urllib.urlopen("http://www.tjoernegaard.dk/Faelles/ElevFotos/"+str(count)+".jpg")
        if resp.getcode() == 404:
          //do nothing
        else:
        // do what you got to do.
    
       count=count+1
    

    【讨论】:

      【解决方案4】:

      我认为最简单的方法是使用wget 而不是curl,它会自动丢弃 404 响应。

      【讨论】:

        【解决方案5】:

        这是旧的,但我发现在 bash 中你可以使用 --fail 并且它会静默失败。如果页面出错,则不会下载...

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2019-09-19
          • 1970-01-01
          • 1970-01-01
          • 2015-06-25
          • 1970-01-01
          • 2019-08-20
          • 2023-03-28
          相关资源
          最近更新 更多