Python實現(xiàn)批量下載文件
更新時間:2015年05月17日 12:11:45 投稿:hebedich
之前給大家分享的python 多線程抓取網(wǎng)頁,不過這個只能用python 來抓取到網(wǎng)頁的源代碼,如果你想用做python 下載文件的話,上面的可能就不適合你了,最近我在用python 做文件下載的時候就遇到這個問題了,不過最終得以解決,我把代碼發(fā)出來
Python實現(xiàn)批量下載文件
#!/usr/bin/env python
# -*- coding:utf-8 -*-
from gevent import monkey
monkey.patch_all()
from gevent.pool import Pool
import requests
import sys
import os
def download(url):
chrome = 'Mozilla/5.0 (X11; Linux i86_64) AppleWebKit/537.36 ' +
'(KHTML, like Gecko) Chrome/41.0.2272.101 Safari/537.36'
headers = {'User-Agent': chrome}
filename = url.split('/')[-1].strip()
r = requests.get(url.strip(), headers=headers, stream=True)
with open(filename, 'wb') as f:
for chunk in r.iter_content(chunk_size=1024):
if chunk:
f.write(chunk)
f.flush()
print filename,"is ok"
def removeLine(key, filename):
os.system('sed -i /%s/d %s' % (key, filename))
if __name__ =="__main__":
if len(sys.argv) == 2:
filename = sys.argv[1]
f = open(filename,"r")
p = Pool(4)
for line in f.readlines():
if line:
p.spawn(download, line.strip())
key = line.split('/')[-1].strip()
removeLine(key, filename)
f.close()
p.join()
else:
print 'Usage: python %s urls.txt' % sys.argv[0]
其他網(wǎng)友的方法:
from os.path import basename
from urlparse import urlsplit
def url2name(url):
return basename(urlsplit(url)[2])
def download(url, localFileName = None):
localName = url2name(url)
req = urllib2.Request(url)
r = urllib2.urlopen(req)
if r.info().has_key('Content-Disposition'):
# If the response has Content-Disposition, we take file name from it
localName = r.info()['Content-Disposition'].split('filename=')[1]
if localName[0] == '"' or localName[0] == "'":
localName = localName[1:-1]
elif r.url != url:
# if we were redirected, the real file name we take from the final URL
localName = url2name(r.url)
if localFileName:
# we can force to save the file as specified name
localName = localFileName
f = open(localName, 'wb')
f.write(r.read())
f.close()
download(r'你要下載的python文件的url地址')
以上便是本文給大家分享的全部內容了,小伙伴們可以測試下哪種方法效率更高呢。
相關文章
Python實現(xiàn)合并同一個文件夾下所有txt文件的方法示例
這篇文章主要介紹了Python實現(xiàn)合并同一個文件夾下所有txt文件的方法,涉及Python針對文件的遍歷、讀取、寫入等相關操作技巧,需要的朋友可以參考下2018-04-04
用Python進行柵格數(shù)據(jù)的分區(qū)統(tǒng)計和批量提取
該教程其實源于web,我看到之后覺得很實用,于是自己又重復做了一遍,寫了詳細的注釋分享給大家,希望對大家的研究有幫助,本文講述了柵格的分區(qū)統(tǒng)計,批量提取,深化理解遍歷循環(huán)等內容2021-05-05
Python爬蟲之Selenium多窗口切換的實現(xiàn)
這篇文章主要介紹了Python爬蟲之Selenium多窗口切換的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
2020-12-12 
