Python小腳本程序
阿新 • • 發佈:2018-06-10
nload with note con out \n 錯誤 blank com
本文旨在搜集最簡單最原子性的代碼塊,簡單清晰容易閱讀,然後由用戶自己組合。Python代碼排版請自行修改。
這裏是索引目錄:
1. 下載網站文件
2. 下載網站多個文件
1. 下載網站文件
import urllib2 import os //偽造瀏覽器頭,模仿瀏覽器訪問 //否則很多網站會拒絕訪問 出現403錯誤 headers = {‘User-Agent‘:‘Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.6) Gecko/20091201 Firefox/3.5.6‘}
url = ‘https://abc.com/newnotes/a66.mp3‘ req = urllib2.Request(url, headers=headers) //若文件很大,請修改 timeout f = urllib2.urlopen(req,timeout=10) data = f.read() //本地保存的文件名 local = os.path.join(‘/Users/mymac/Desktop/Piano‘,‘a66.mp3‘) with open(local, "wb") as code: code.write(data)
2. 下載網站多個文件
如: http://abc.com/a1.mp3 a2.mp3 a99.mp3
import urllib2 import os headers = {‘User-Agent‘:‘Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.6) Gecko/20091201 Firefox/3.5.6‘} for i in range(1,100): mp3name = ‘b‘ + str(i) +‘.mp3‘ url = ‘https://abc.com/newnotes/‘ + mp3nameprint url req = urllib2.Request(url, headers=headers) //下載出錯則跳過 try: f = urllib2.urlopen(req,timeout=1000) except urllib2.URLError, err: print ‘no file or download error...\n‘ continue data = f.read() local = os.path.join(‘/Users/mymac/Desktop/myfile‘,mp3name) with open(local, "wb") as code: code.write(data)
Python小腳本程序