通过urllib和python下载图片

所以我试图制作一个Python脚本来下载webcomics并把它们放在我的桌面上的一个文件夹中。 我在这里发现了一些类似的程序,做了类似的事情,但没有什么比我所需要的更多。 我发现最相似的就在这里( http://bytes.com/topic/python/answers/850927-problem-using-urllib-download-images )。 我试着用这个代码:

>>> import urllib >>> image = urllib.URLopener() >>> image.retrieve("comics/00000001.jpg","00000001.jpg") ('00000001.jpg', <httplib.HTTPMessage instance at 0x1457a80>) 

然后我search了我的计算机上的“00000001.jpg”文件,但是我发现的只是caching的图片。 我什至不知道它保存到我的电脑的文件。 一旦我明白如何获得文件下载,我想我知道如何处理其余的。 基本上只是使用for循环,并将string拆分为“00000000”,“jpg”和将“00000000”增加到最大的数字,我必须以某种方式确定。 任何reccomendations最好的方式来做到这一点或如何正确下载文件?

谢谢!

编辑6/15/10

这是完整的脚本,它将文件保存到您select的任何目录。 由于一些奇怪的原因,这些文件没有下载,他们只是做了。 任何build议如何清理它将不胜感激。 我目前正在研究如何找出网站上存在的许多漫画,所以我可以得到最新的漫画,而不是在发生一定数量的exception之后退出程序。

 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 

使用urllib.urlretrieve :

 import urllib urllib.urlretrieve("comics/00000001.jpg", "00000001.jpg") 
 import urllib f = open('00000001.jpg','wb') f.write(urllib.urlopen('comics/00000001.jpg').read()) f.close() 

只是为了logging,使用请求库。

 import requests f = open('00000001.jpg','wb') f.write(requests.get('comics/00000001.jpg').content) f.close() 

虽然它应该检查requests.get()错误。

我find了这个答案,并以更可靠的方式进行编辑

 def download_photo(self, img_url, filename): try: image_on_web = urllib.urlopen(img_url) if image_on_web.headers.maintype == 'image': buf = image_on_web.read() path = os.getcwd() + DOWNLOADED_IMAGE_PATH file_path = "%s%s" % (path, filename) downloaded_image = file(file_path, "wb") downloaded_image.write(buf) downloaded_image.close() image_on_web.close() else: return False except: return False return True 

从这里你永远不会得到任何其他资源或下载时的例外。

Python 3版的@DiGMi的回答:

 from urllib import request f = open('00000001.jpg', 'wb') f.write(request.urlopen("comics/00000001.jpg").read()) f.close() 

使用.read()读取部分或整个响应,然后将其写入已打开的文件中,这是最容易的。

也许你需要'用户代理':

 import urllib2 opener = urllib2.build_opener() opener.addheaders = [('User-Agent', 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.137 Safari/537.36')] response = opener.open('http://google.com') htmlData = response.read() f = open('file.txt','w') f.write(htmlData ) f.close() 

如果您知道这些文件位于网站的同一目录dir中,并具有以下格式:filename_01.jpg,…,filename_10.jpg然后下载所有这些文件:

 import requests for x in range(1, 10): str1 = 'filename_%2.2d.jpg' % (x) str2 = 'http://site/dir/filename_%2.2d.jpg' % (x) f = open(str1, 'wb') f.write(requests.get(str2).content) f.close() 

除了build议你仔细阅读retrieve()的文档( http://docs.python.org/library/urllib.html#urllib.URLopener.retrieve ),我会build议实际调用read()的响应内容,然后将其保存到您select的文件中,而不是将其保留在检索创build的临时文件中。

所有上面的代码,不允许保留原始图像的名称,有时是必需的。 这将有助于将图像保存到本地驱动器,保留原始图像名称

  IMAGE = URL.rsplit('/',1)[1] urllib.urlretrieve(URL, IMAGE) 

试试这个更多的细节。

对于Python 3,您需要导入import urllib.request

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

欲了解更多信息,请查看链接

更简单的解决scheme可能是(python 3):

 import urllib.request import os os.chdir("D:\\comic") #your path i=1; s="00000000" while i<1000: try: urllib.request.urlretrieve("http://www.gunnerkrigg.com//comics/"+ s[:8-len(str(i))]+ str(i)+".jpg",str(i)+".jpg") except: print("not possible" + str(i)) i+=1; 

那这个呢:

 import urllib, os def from_url( url, filename = None ): '''Store the url content to filename''' if not filename: filename = os.path.basename( os.path.realpath(url) ) req = urllib.request.Request( url ) try: response = urllib.request.urlopen( req ) except urllib.error.URLError as e: if hasattr( e, 'reason' ): print( 'Fail in reaching the server -> ', e.reason ) return False elif hasattr( e, 'code' ): print( 'The server couldn\'t fulfill the request -> ', e.code ) return False else: with open( filename, 'wb' ) as fo: fo.write( response.read() ) print( 'Url saved as %s' % filename ) return True ## def main(): test_url = 'http://cdn.sstatic.net/stackoverflow/img/favicon.ico' from_url( test_url ) if __name__ == '__main__': main()