下载天涯的文章
写了个下载天涯文章的Python脚本,有点乱,效率很低,单线程,用正则表达式拼起来的。
能简单的判断一些是不是作者与网友聊天的帖子,也会有失误,而且很多!!!!
有时候会卡死,我的解决办法是重新来一次……汗
# -*- coding: utf-8 -*- import urllib import urllib2 import re,osdef cn(s):return s.decode("utf-8").encode("gbk")def getUrlContent(url):return urllib2.urlopen(url).read()def getFirst(cont):p1 = re.findall('''<div class="bbs-content clearfix">(.+?)</div>''',cont,re.DOTALL)if len(p1)>0:return p1[0]else:return ""def getNextPageUrl(cont):p1 = re.findall('''<a href="(.+?)" class="js-keyboard-next">下页</a>''',cont)if len(p1)>0:return "http://bbs.tianya.cn"+p1[0]else:return Nonedef getAuthor(cont):p1 = re.findall('''<meta name="author" content="(.+)">''',cont)if len(p1)>0:return p1[0]def getTitle(cont): p1 = re.findall('''<span class="s_title"><span style="font-weight:400;">(.+?)</span>''',cont)if len(p1)>0:return p1[0]def getOnePage(cont,author,fp):t=""n=0#print contp='''<div class="atl-item".+?uname="(.+?)">.+?<span>(时间.+?)</span>.+?<div class="bbs-content">(.+?)</div>'''p1 = re.findall(p,cont,re.S)#print p1if len(p1)>0:for t in p1:if t[0]==author:if re.findall("[^-]+?-----------------------------[^-]*?",t[2])==[] and len(t[2])>512:fp.writelines("<hr/>%s<br/>%s"%(t[1],t[2]))def main(url):n=0author=""print urlcont=getUrlContent(url)if cont<0:returnprint 'open OK'author=getAuthor(cont)if author<0:print "url error"returntitle = getTitle(cont)if author<0:print "url error"returntime=re.findall("<span>(时间:.+?)</span>",cont)[0]print 'title:',cn(title)print 'author:',cn(author)print 'time:',cn(time)while 1:if n>0:fn="%s[%d].htm"%(cn(title),n)else:fn="%s.htm"%cn(title)if os.path.isfile(fn):print "File %s already exists!"%fnn=n+1else:breakfp=open(fn,'w')fp.writelines('''<html><head><meta charset="utf-8"/><title>%s</title></head><body>'''%(title))fp.writelines("【%s】<br/>【%s】\n<hr/>%s<br/>"%(title,author,time))fp.writelines(getFirst(cont))n=1while 1:print "page:%d"%ngetOnePage(cont,author,fp)url=getNextPageUrl(cont)if url!=None:cont=getUrlContent(url)n=n+1else:breakfp.writelines('''</body></html>''')fp.close()print "download ok"if __name__ == '__main__':url=raw_input('input url:')main(url)
转载于:https://www.cnblogs.com/fwindpeak/p/3369383.html
总结
- 上一篇: web.xml 通过contextCon
- 下一篇: mybatis实战教程(mybatis