【问题标题】:Python save images from URL to different folders with custom name and structurePython将图像从URL保存到具有自定义名称和结构的不同文件夹
【发布时间】:2020-04-07 10:55:22
【问题描述】:

我有一个带有图像 URL 的 .csv 文件,我需要将每个图像保存在不同的文件夹中,例如 URL 中的树。比如这里3个网址

https://citynews.stgy.ovh/~shared/uploads/files/794/794964898449/62325865102181/logo_1.pic
https://citynews.stgy.ovh/~shared/uploads/files/420/42030573107817/62325865102181/logo_1.pic
https://citynews.stgy.ovh/~shared/uploads/files/218/21897603939378/62325865102181/logo_1.pic

我需要将每张图片保存在名为路径 url 的不同文件夹树中,如下所示:

  • 图像 1 -> 文件夹 /uploads/files/794/7949​​64898449/62325865102181/
  • 图像 2 -> 文件夹 /uploads/files/420/42030573107817/62325865102181/
  • 图像 3 -> 文件夹 /uploads/files/218/21897603939378/62325865102181/

【问题讨论】:

    标签: python python-3.x web-scraping


    【解决方案1】:

    应该这样做:

    import os
    import urllib.request as urllib2
    
    BASE_DIR = "C:\\workspace"
    
    urls = ["https://citynews.stgy.ovh/~shared/uploads/files/794/794964898449/62325865102181/logo_1.pic",
            "https://citynews.stgy.ovh/~shared/uploads/files/420/42030573107817/62325865102181/logo_1.pic",
            "https://citynews.stgy.ovh/~shared/uploads/files/218/21897603939378/62325865102181/logo_1.pic"
            ]
    
    for url in urls:
        split_path = url.split("~shared/")[1]
        img_name = os.path.basename(split_path)
        dir_name = os.path.dirname(split_path)
        path = os.path.join(BASE_DIR, dir_name)
        print(path)
        os.makedirs(path, exist_ok = True)
        urllib2.urlretrieve(url, os.path.join(path, img_name))
    
    print("done")
    

    另外,请阅读此链接:python-os-makedirs

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-27
      • 2021-12-30
      • 1970-01-01
      • 2017-04-25
      • 2019-09-03
      • 2013-05-20
      相关资源
      最近更新 更多