Python小脚本程序
Posted 明明如月
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python小脚本程序相关的知识,希望对你有一定的参考价值。
本文旨在搜集最简单最原子性的代码块,简单清晰容易阅读,然后由用户自己组合。Python代码排版请自行修改。
这里是索引目录:
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)
如: 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/‘ + mp3name print url req = urllib2.Request(url, headers=headers) //下载出错则跳过 try: f = urllib2.urlopen(req,timeout=1000) except urllib2.URLError, err: print ‘no file or download error... ‘ continue data = f.read() local = os.path.join(‘/Users/mymac/Desktop/myfile‘,mp3name) with open(local, "wb") as code: code.write(data)
以上是关于Python小脚本程序的主要内容,如果未能解决你的问题,请参考以下文章