RCmerci

无聊写一个浏览糗事百科控制台代码

# -*- coding: utf-8 -*-
import urllib2,urllib,re
import threading,time,sys

class TOOL:
    URL = r'http://www.qiushibaike.com/hot/page/'
    URL_late = r'http://www.qiushibaike.com/late/page/'
    re_content = re.compile(r'title="201(.|\s)+?\>\s+(.+?)\s+?\</div\>\s+?\<div id=')#取第二个group
    class MyThread(threading.Thread):
        def __init__(self,func,args = ()):
            super(TOOL.MyThread,self).__init__()
            self.func = func
            self.args = args
        def run(self):
            apply(self.func,self.args)


class Engine:
    def __init__(self):
        self.pages = []
        self.page_num = 1
        self.show_num_everytime = 5
        self.content_for_show = []
        self.url=''
        self.choice = 1
    def start(self):
        self.choose()
        self.__load_page()
        self.__loading_hint()
        print u'按键显示内容'
        raw_input()
        while 1:
            self.__show_page()
        pass
    def __load_page(self):
        mythread = TOOL.MyThread(self.__get_pages)
        mythread.setDaemon(True)
        mythread.start()
    def __show_page(self):
        if len(self.pages):
            for i in self.pages[0]:
                if len(i) > 4:
                    try:
                        self.content_for_show.append(i)
                        if len(self.content_for_show)>=5:
                            for j in self.content_for_show:
                                print j.decode('utf-8')
                                print '-'*79
                            raw_input('more...')
                            print '*'*80
                            self.content_for_show=[]
                    except:
                        self.content_for_show=[]
                        print '*'*80
            self.pages.pop(0)
        else:
            self.__wait()

    def __get_pages(self):
        while 1:
            if len(self.pages) < 2:
                content = urllib2.urlopen(self.url+str(self.page_num)).read()
                self.pages.append([i[1] for i in re.findall(TOOL.re_content,content)])
                self.page_num+=1
            else:
                time.sleep(1)
    def __loading_hint(self):
        print u'加载中...'
        time.sleep(2)
    def __wait(self):
        print u'加载中。。'
        time.sleep(2)
    def choose(self):
        print u'选择 1.最新(default) 2.精华'
        try:
            self.choice = input()
        except:
            self.choice = 1
        if self.choice == 2:
            self.url = TOOL.URL
        else:
            self.url = TOOL.URL_late
if __name__ == '__main__':
    print '#'*80
    print u'''
                       控制台版
          2013-12-11
          糗百
          python 2.7.5
          '''
    print '#'*80
    engine = Engine()
    engine.start()

posted on 2013-12-11 11:16  RCmerci  阅读(194)  评论(0)    收藏  举报

导航