您的位置:首页 > 编程语言 > Python开发

从Python爬虫到SAE云和微信公众号:一、糗事百科爬虫

2017-01-03 19:11 330 查看
这是写给自己玩的练习项目,从糗事百科中爬取段子放到微信公众号上去,这样我就能随时随地的看段子了,啊哈哈哈

项目结构

1.糗事百科爬虫:Pthon实现,MySQL做持久化存储

2.用免费的新浪SAE云搭建微信公众号的服务器

3.微信公众号部分

# coding:utf8
import re

class HtmlParser(object):
#auther AllenRobin  cnblogs.com/GISRSMAN/
# 将所有的段子都扣出来,添加到列表中并且返回列表
def __init__(self):
self.storys=[]
self.keywords=[]
self.nextUrlCode=''

#获得笑话正文、当前页Code、下一页Code
def GetStorys(self,page):
# print myPage
unicodePage = page.decode("utf-8")
# 找出所有class="content"的div标记
#re.S是任意匹配模式,也就是.可以匹配换行符
#myItems = re.findall('<div.*?class="content">(.*?)</div>',unicodePage,re.S)
myItems = re.findall('<div.*?class="content">\n\n+<span>(.*?)</span>\n\n+</div>',unicodePage,re.S)
thisUrlCode=re.findall('<link rel="canonical" href="http://www.qiushibaike.com/history/(.*?)/">',unicodePage,re.S)[0]
nextUrlCode=re.findall('<a class="random" href="/history/(.*?)/".*?',unicodePage,re.S)[0]

return myItems,thisUrlCode,nextUrlCode

#获得笑话正文(作者赞数)、当前页Code、下一页Code
def GetStorys2(self,pageContent):
try:
unicodePage= pageContent.decode("utf-8")
pattern = re.compile('<div class="author clearfix">.*?<h2>(.*?)</h2>.*?<div.*?' +'content">\n\n+<span>(.*?)</span>\n\n+</div>(.*?)<span class="stats-vote"><i class="number">(.*?)</i>',re.S)

#items三个要素依次为用户名、段子内容、赞数
items = re.findall(pattern, pageContent)

for item in items:
#去除段子内容中的查看全文
item[1].replace("<span class=\"contentForAll\">查看全文","").replace("</span>","").replace("'","\"")
#除去含有图片的
haveImg = re.search("img", item[3])
if  haveImg:
print item
del item

#可以将这三个合并到上一个提高效率
thisUrlCode = re.findall('<link rel="canonical" href="http://www.qiushibaike.com/history/(.*?)/">', unicodePage, re.S)[0]
nextUrlCode = re.findall('<a class="random" href="/history/(.*?)/".*?', unicodePage, re.S)[0]
dateStrs = re.findall('<meta name="keywords" content="(.*?)" />', unicodePage, re.S)[0]

return items,thisUrlCode,nextUrlCode,dateStrs
except Exception, e:
print Exception, ":", e


页面解析代码

整个爬虫项目放到Github上吧,欢迎fork

GitHub地址:https://github.com/csdallen/qiushi_history_spider

参考资源:

Python开发简单爬虫

Python爬虫实战一之爬取糗事百科段子
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: