我想解析所有img標籤的html,下載src指向的所有圖像,然後將這些文件添加到zip文件。我寧願在記憶中做所有這些,因爲我可以保證不會有那麼多的圖像。解析html文件並將找到的圖像添加到zip文件
假設圖像變量已經從解析html中填充。我需要幫助的是將圖像放入zip文件中。
from zipfile import ZipFile
from StringIO import StringIO
from urllib2 import urlopen
s = StringIO()
zip_file = ZipFile(s, 'w')
try:
for image in images:
internet_image = urlopen(image)
zip_file.writestr('some-image.jpg', internet_image.fp.read())
# it is not obvious why I have to use writestr() instead of write()
finally:
zip_file.close()
使用的urllib2/LXML/XPath的/谷歌 – mykhal 2009-12-22 22:22:51
第二布萊恩·阿格紐的言論,看起來你已經差不多把一切都整理。你必須使用zip_file.writestr(),因爲你是從一個字節緩衝區(即:一個字節字符串)寫入數據,而不是從位於文件系統上的文件(這是zip_file.write()希望接收的文件)。 – 2009-12-22 23:29:37
不要忘記其中引用的樣式表和圖像... – 2013-08-19 21:37:28