Python爬虫实战(一):爬糗事百科段子
2023-09-14 08:59:06 时间
代码:
# _*_ 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】python 多线程两种实现方式
- [python]赶集网二手房爬虫插件【可用任意扩展】
- 小白学 Python 爬虫(40):爬虫框架 Scrapy 入门基础(七)对接 Selenium 实战
- 小白学 Python 爬虫(26):为啥上海二手房你都买不起
- 小白学 Python 爬虫(16):urllib 实战之爬取妹子图
- 【Python实战】python中含有中文字符无法运行
- Python爬虫实战(一):爬糗事百科段子
- 靠着自学python,我兼职拿到了进入编程行业的第一桶金!
- Python语言学习:Python语言学习之网络爬虫/反爬虫技术相关的简介、案例应用之详细攻略
- Python IDE之Pydev: 基于Eclipse搭建python的编译环境(Eclipse+pydev)简介、安装、使用技巧方法集合之详细攻略
- 已解决Python爬虫网页中文乱码问题
- 使用Python进行爬虫的初学者指南,含案例演示
- Python爬虫实战,Request+urllib模块,批量下载爬取飙歌榜所有音乐文件
- 18个Python爬虫实战案例
- 从零开始学习python | 实例讲解如何制作Python模式程序
- Python编程:查看python环境支持的whl
- Python爬虫:requests库基本使用
- 雅虎财经数据python 网络爬虫stock股票 用 Python 通过雅虎财经获取股票数据
- python 爬虫 循环分页
- python-手写数字识别改进+TensorBoard(TensorFlow可视化)
- 10个Python爬虫入门实例
- 【python】Python实现网络爬虫demo实例
- Python爬虫实战(一):翻页爬取数据存入SqlServer
- python 网站爬虫需要哪些技术?
- 〖Python自动化办公篇⑲〗 - python实现邮件自动化 - 邮件发送
- Python爬虫进行BeautifulSoup数据解析实战
- 从零开始,学会Python爬虫不再难!!! -- (13)selenium项目:自动点赞机丨蓄力计划