【问题标题】:Python - Saving an image from a url [duplicate]Python - 从网址保存图像[重复]
【发布时间】:2011-05-17 01:10:22
【问题描述】:

有没有办法使用 urllib 或 Beautiful Soup 从 url 保存图片?

-谢谢

【问题讨论】:

    标签: python beautifulsoup urllib


    【解决方案1】:

    你想要urllib.urlretrieve()

    【讨论】:

      【解决方案2】:

      不需要 Beautiful Soup,因为我假设您需要读取二进制文件。 只需读取流并将其存储为文件即可。

      import urllib                                       
      url = "http://example.com/file.pdf"
      uopen = urllib.urlopen(url)
      stream = uopen.read()
      file = open('filename','w')
      file.write(stream)
      file.close()
      

      顺便说一句。解决多千兆图像问题

      import urllib
      urllib.urlretrieve('url', 'filename')
      

      第二个代码 sn-p 会更可靠.. 感谢Ignacio Vazquez-Abrams 启发这个大文件问题。

      【讨论】:

        【解决方案3】:

        这是为我自己写的。

        def get_file(url):
            file_temp = NamedTemporaryFile()
            file_temp.write(urllib2.urlopen(url).read())
            file_temp.flush()
            return File(file_temp)
        

        【讨论】:

          【解决方案4】:

          在读取数据的同时写入文件。

          from urllib.request import urlopen
          
          local_file_name = 'localfile.txt'
          remote_url = 'http://localhost/example'
          
          remote_file = urlopen(remote_url)
          local_file = open(file_name, "w")
          local_file.write(remote_file.read())
          local_file.close()
          

          【讨论】:

          • 这是一个不温不火的例子,尽管您不会遇到很多数 GB 的图像。
          • 太好了,非常感谢! :D
          • 虽然此链接可能会回答问题,但最好在此处包含答案的基本部分并提供链接以供参考。如果链接页面发生更改,仅链接的答案可能会失效
          猜你喜欢
          • 2011-11-29
          • 2015-12-24
          • 2021-02-28
          • 2018-01-18
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-06-24
          相关资源
          最近更新 更多