通过urllib和Python下载图片
我正在尝试写一个Python脚本,用来下载网络漫画,并把它们放到我桌面上的一个文件夹里。我在这里找到了一些类似的程序,但没有一个完全符合我的需求。我找到的最相似的一个在这里(http://bytes.com/topic/python/answers/850927-problem-using-urllib-download-images)。我试着用这个代码:
>>> import urllib
>>> image = urllib.URLopener()
>>> image.retrieve("http://www.gunnerkrigg.com//comics/00000001.jpg","00000001.jpg")
('00000001.jpg', <httplib.HTTPMessage instance at 0x1457a80>)
然后我在我的电脑上搜索了一个名为“00000001.jpg”的文件,但我只找到了它的缓存图片。我甚至不确定它是否真的把文件保存到我的电脑上。一旦我明白怎么下载文件,我想我就知道怎么处理后面的事情。基本上就是用一个循环,把字符串在'00000000'和'.jpg'之间分开,然后把'00000000'的数字加大,直到最大的数字,这个最大数字我得想办法确定。你有什么好的建议,能让我正确下载文件吗?
谢谢!
编辑 2010年6月15日
这是完成的脚本,它可以把文件保存到你选择的任何目录。奇怪的是,文件之前没有下载,现在却下载成功了。任何关于如何优化它的建议都非常感谢。我现在正在研究如何找出网站上有多少漫画,这样我就可以只获取最新的一部,而不是让程序在遇到一定数量的错误后就停止。
import urllib
import os
comicCounter=len(os.listdir('/file'))+1 # reads the number of files in the folder to start downloading at the next comic
errorCount=0
def download_comic(url,comicName):
"""
download a comic in the form of
url = http://www.example.com
comicName = '00000000.jpg'
"""
image=urllib.URLopener()
image.retrieve(url,comicName) # download comicName at URL
while comicCounter <= 1000: # not the most elegant solution
os.chdir('/file') # set where files download to
try:
if comicCounter < 10: # needed to break into 10^n segments because comic names are a set of zeros followed by a number
comicNumber=str('0000000'+str(comicCounter)) # string containing the eight digit comic number
comicName=str(comicNumber+".jpg") # string containing the file name
url=str("http://www.gunnerkrigg.com//comics/"+comicName) # creates the URL for the comic
comicCounter+=1 # increments the comic counter to go to the next comic, must be before the download in case the download raises an exception
download_comic(url,comicName) # uses the function defined above to download the comic
print url
if 10 <= comicCounter < 100:
comicNumber=str('000000'+str(comicCounter))
comicName=str(comicNumber+".jpg")
url=str("http://www.gunnerkrigg.com//comics/"+comicName)
comicCounter+=1
download_comic(url,comicName)
print url
if 100 <= comicCounter < 1000:
comicNumber=str('00000'+str(comicCounter))
comicName=str(comicNumber+".jpg")
url=str("http://www.gunnerkrigg.com//comics/"+comicName)
comicCounter+=1
download_comic(url,comicName)
print url
else: # quit the program if any number outside this range shows up
quit
except IOError: # urllib raises an IOError for a 404 error, when the comic doesn't exist
errorCount+=1 # add one to the error count
if errorCount>3: # if more than three errors occur during downloading, quit the program
break
else:
print str("comic"+ ' ' + str(comicCounter) + ' ' + "does not exist") # otherwise say that the certain comic number doesn't exist
print "all comics are up to date" # prints if all comics are downloaded
20 个回答
84
只是为了说明,这里使用的是requests库。
import requests
f = open('00000001.jpg','wb')
f.write(requests.get('http://www.gunnerkrigg.com//comics/00000001.jpg').content)
f.close()
不过应该检查一下requests.get()是否出错。
101
Python 2:
import urllib
f = open('00000001.jpg','wb')
f.write(urllib.urlopen('http://www.gunnerkrigg.com//comics/00000001.jpg').read())
f.close()
Python 3:
import urllib.request
f = open('00000001.jpg','wb')
f.write(urllib.request.urlopen('http://www.gunnerkrigg.com//comics/00000001.jpg').read())
f.close()
298
Python 2
使用 urllib.urlretrieve 这个工具来下载文件。
import urllib
urllib.urlretrieve("http://www.gunnerkrigg.com//comics/00000001.jpg", "00000001.jpg")
Python 3
使用 urllib.request.urlretrieve (这是Python 3中的一个旧版接口,功能和Python 2的一样)来下载文件。
import urllib.request
urllib.request.urlretrieve("http://www.gunnerkrigg.com//comics/00000001.jpg", "00000001.jpg")