fork download
  1. # -*- coding: utf-8 -*-
  2.  
  3. import urllib2
  4. import urllib
  5. import re
  6. import thread
  7. import time
  8.  
  9.  
  10. #----------- 加载处理糗事百科 -----------
  11. class Spider_Model:
  12.  
  13. def __init__(self):
  14. self.page = 1
  15. self.pages = []
  16. self.enable = False
  17.  
  18. # 将所有的段子都扣出来,添加到列表中并且返回列表
  19. def GetPage(self,page):
  20. myUrl = "http://m...content-available-to-author-only...e.com/hot/page/" + page
  21. user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
  22. headers = { 'User-Agent' : user_agent }
  23. req = urllib2.Request(myUrl, headers = headers)
  24. myResponse = urllib2.urlopen(req)
  25. myPage = myResponse.read()
  26. #encode的作用是将unicode编码转换成其他编码的字符串
  27. #decode的作用是将其他编码的字符串转换成unicode编码
  28. unicodePage = myPage.decode("utf-8")
  29. # print unicodePage
  30.  
  31. # 找出所有class="content"的div标记
  32. #re.S是任意匹配模式,也就是.可以匹配换行符
  33. myItems = re.findall('<div.*?class="content".*?title="(.*?)">(.*?)</div>',unicodePage,re.S)
  34. items = []
  35. for item in myItems:
  36. # item 中第一个是div的标题,也就是时间
  37. # item 中第二个是div的内容,也就是内容
  38. items.append([item[0].replace("\n",""),item[1].replace("\n","")])
  39. return items
  40.  
  41. # 用于加载新的段子
  42. def LoadPage(self):
  43. # 如果用户未输入quit则一直运行
  44. while self.enable:
  45. # 如果pages数组中的内容小于2个
  46. if len(self.pages) < 2:
  47. try:
  48. # 获取新的页面中的段子们
  49. myPage = self.GetPage(str(self.page))
  50. self.page += 1
  51. self.pages.append(myPage)
  52. except:
  53. print '无法链接糗事百科!'
  54. else:
  55. time.sleep(1)
  56.  
  57. def ShowPage(self,nowPage,page):
  58. for items in nowPage:
  59. print u'第%d页' % page , items[0] , items[1]
  60. myInput = raw_input()
  61. if myInput == "quit":
  62. self.enable = False
  63. break
  64.  
  65. def Start(self):
  66. self.enable = True
  67. page = self.page
  68.  
  69. print u'正在加载中请稍候......'
  70.  
  71. # 新建一个线程在后台加载段子并存储
  72. thread.start_new_thread(self.LoadPage,())
  73.  
  74. #----------- 加载处理糗事百科 -----------
  75. while self.enable:
  76. # 如果self的page数组中存有元素
  77. if self.pages:
  78. nowPage = self.pages[0]
  79. del self.pages[0]
  80. self.ShowPage(nowPage,page)
  81. page += 1
  82.  
  83.  
  84. #----------- 程序的入口处 -----------
  85. print u"""
  86. ---------------------------------------
  87. 程序:糗百爬虫
  88. 版本:0.3
  89. 作者:why
  90. 日期:2014-06-03
  91. 语言:Python 2.7
  92. 操作:输入quit退出阅读糗事百科
  93. 功能:按下回车依次浏览今日的糗百热点
  94. ---------------------------------------
  95. """
  96.  
  97.  
  98. print u'请按下回车浏览今日的糗百内容:'
  99. raw_input(' ')
  100. myModel = Spider_Model()
  101. myModel.Start()
  102.  
Runtime error #stdin #stdout #stderr 0.04s 12848KB
stdin
Standard input is empty
stdout
Standard output is empty
stderr
Traceback (most recent call last):
  File "prog.py", line 95, in <module>
UnicodeEncodeError: 'ascii' codec can't encode characters in position 46-52: ordinal not in range(128)