Python - 从网址保存图片
有没有办法用urllib或者Beautiful Soup从一个网址保存一张图片呢?
-谢谢
4 个回答
3
其实你不需要用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')
第二段代码会更可靠,感谢Ignacio Vazquez-Abrams
指出了大文件的问题。
5
你需要用到 urllib.urlretrieve()
这个功能。
-1
简单来说,就是在读取数据的同时,把这些数据写入一个文件里。
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()