码迷,mamicode.com
首页 > 编程语言 > 详细

Python爬虫实战(一):爬糗事百科段子

时间:2015-11-26 12:39:47      阅读:137      评论:0      收藏:0      [点我收藏+]

标签:

代码:

# _*_ coding:utf-8 _*_
import urllib2
import re
from datetime import datetime

class QSBK:
    def __init__(self):
        self.pageIndex = 1
        self.user_agent = ‘Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)‘
        self.headers = {‘User-Agent‘:self.user_agent}
        self.stories = []
        self.enable = False
        
    def getPage(self,pageIndex):
        try:
            url = ‘http://www.qiushibaike.com/hot/page‘+str(pageIndex)
            request = urllib2.Request(url,headers = self.headers)
            response = urllib2.urlopen(request)
            pageCode = response.read().decode(‘utf-8‘)
            return pageCode
        except urllib2.URLError,e:
            if hasattr(e,‘reason‘):
                print u"QSBK connect Error,reason: ",e.reason
                return None

    def getPageItems(self,pageIndex):
        pageCode = self.getPage(pageIndex)
        if not pageCode:
            print "Page Loading Error..."
            return None
        pattern = re.compile(‘<div.*?author clearfix">.*?<a.*?<img.*?>(.*?)</a>.*?<a.*?<h2>(.*?)</h2>.*?</a>.*?<div.*?‘+‘content">(.*?)<!--(.*?)-->.*?</div>.*?<div class="stats.*?class="number">(.*?)</i>‘,re.S)
        items = re.findall(pattern,pageCode)
        pageStories = []
        for item in items:
            haveImg = re.search("img",item[0])
            if not haveImg:
                replaceBR = re.compile(‘<br/>‘)
                text = re.sub(replaceBR,"\n",item[2])
                pageStories.append([item[1].strip(),text.strip(),item[3].strip(),item[4].strip()])
        return pageStories

    def loadPage(self):
        if self.enable == True:
            if len(self.stories) < 2:
                pageStories = self.getPageItems(self.pageIndex)
                if pageStories:
                    self.stories.append(pageStories)
                    self.pageIndex += 1

    def getOneStory(self,pageStories,page):
         for story in pageStories:
             input = raw_input()
             self.loadPage()
             if input == ‘Q‘:
                 self.enable = False
                 return
             print u"第%d页\t发布人:%s\t发布时间:%s\t赞:%s\n%s" %(page,story[0],datetime.fromtimestamp(int(story[2])),story[3],story[1])
             
    def start(self):
         print u"正在读取糗事百科,按回车查看新段子,Q退出"
         self.enable = True
         self.loadPage()
         nowPage = 0
         while self.enable:
             if len(self.stories)>0:
                 pageStories = self.stories[0]
                 nowPage += 1
                 del self.stories[0]
                 self.getOneStory(pageStories,nowPage)

spider = QSBK()
spider.start()

  

Python爬虫实战(一):爬糗事百科段子

标签:

原文地址:http://www.cnblogs.com/AndyJee/p/4997101.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!