Python - 从 url 保存图像

发布于 2024-10-04 11:39:20 字数 64 浏览 0 评论 0原文

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

-谢谢

Is there a way to save a picture from a url using urllib or Beautiful Soup?

-Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

假面具 2024-10-11 11:39:20

不需要美丽的汤,因为我假设你需要读取二进制文件。
只需读取流并将其存储为文件即可。

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')

第二个代码片段将更加可靠。感谢 Ignacio Vazquez-Abrams 启发了大文件的问题。

no need of Beautiful Soup as i assume you need to read a binary file.
Just read the stream and store it as a file.

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

btw. to address the issue of multigigabit images

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

2nd code snippet gonna be more reliable.. thanks to Ignacio Vazquez-Abrams enlighten this issue of large files.

你是年少的欢喜 2024-10-11 11:39:20

只是为自己写的。

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

Just wrote this for myself.

def get_file(url):
    file_temp = NamedTemporaryFile()
    file_temp.write(urllib2.urlopen(url).read())
    file_temp.flush()
    return File(file_temp)
灰色世界里的红玫瑰 2024-10-11 11:39:20

只需在读取数据时写入文件即可。

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()

Simply write to a file while reading the data.

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()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文