爬虫入门(1)
来源:互联网 发布:淘宝 软件 编辑:程序博客网 时间:2024/06/13 00:52
# -*- coding:utf-8 -*-import urllibimport urllib2import reimport threadclass QSBK: def __init__(self): self.page_index = 1 self.user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)' self.headers = {"User-Agent": self.user_agent} self.storys = [] def getPage(self): try: url = 'http://www.qiushibaike.com/hot/page/' + str(self.page_index) request = urllib2.Request(url, headers = self.headers) response = urllib2.urlopen(request) page_code = response.read().decode('utf-8', 'ignore') return page_code except urllib2.URLError, e: if hasattr(e, 'reason'): print "连接糗事百科失败,错误原因:", e.reason return None def getPageItem(self): page_code = self.getPage() if not page_code: print "页面加载失败..." return None pattern = re.compile('<div class="author clearfix">.*?<a.*?<img.*?</a>.*?<a.*?<h2>(.*?)</h2>.*?<div.*?"content">(.*?)</div>',re.S) items = re.findall(pattern, page_code) page_storys = [] for item in items: x = item[0] + ':' y = item[1].replace('<br/>', ' ') self.storys.append([x.strip(), y.strip()]) def start(self): print "正在读取糗事百科,回车查看新段子,Q退出..." self.getPageItem() while True: if len(self.storys) > 0: story = self.storys[0] del self.storys[0] input = raw_input() if (input == 'Q') or (input == 'q'): break print u"第%d页\n%s\t \n%s" %(self.page_index, story[0], story[1]) else: self.page_index += 1 self.getPageItem()spider = QSBK()spider.start()
0 0
- 爬虫入门(1)
- scrapy 爬虫入门(1)
- Python爬虫入门(1)
- Python爬虫笔记----爬虫技术入门(1)
- 【python爬虫】python爬虫入门攻略(1)
- Python爬虫入门(1):综述
- Python爬虫入门(1):综述
- 爬虫教程(1)基础入门
- 爬虫入门(一)
- (一)爬虫入门
- python爬虫入门1--爬虫基本结构
- Python 爬虫入门 1 了解爬虫Scrapy
- Python爬虫----爬虫入门(2)
- Python爬虫----爬虫入门(3)---urllib2
- 爬虫入门四(多线程爬虫)
- python 网络爬虫入门 1
- 爬虫入门1:urllib.request
- 爬虫入门1:urllib.parse
- android 联系人 首字母分类 封装(更新)
- 我生命中的钱事:学费!
- C++ 字节对齐专题
- GET和POST的真正区别
- odoo 性能调优以及负载均衡
- 爬虫入门(1)
- mina iobuffer byte[]、String之间转换
- 最大整数 贪心***
- 每天laravel-20160805| Container -8
- 欢迎使用CSDN-markdown编辑器
- go语言学习2
- Android Intent设置类型setType();
- python装饰器(decorator)
- 跳槽最惨的情况,不看要悲剧!