您的位置:首页 > 编程语言 > Python开发

python爬虫小项目:爬取糗事百科段子

2016-11-04 19:37 519 查看
写完这篇文章有一两个月了,中间忙着期末考试等各种事情就没去管它,刚运行了一下代码发现出现了编码错误,在爬取完第一页后,出现以下错误:

UnicodeEncodeError: 'gbk' codec can't encode character '\u22ef' in position 93: illegal multibyte sequence。

在查询了一些资料后,借鉴博客园中相关说明后,在代码开头加上如下声明:

import io
import sys
sys.stdout = io.TextIOWrapper(sys.stdout.buffer,encoding='gb18030') #改变标准输出的默认编码


因为是我是在cmd下运行,所以需要改变标准输出的默认编码,具体说明请大家参照博客园中相关说明

更新时间:2017/1/12

====================================================================================================================================

python爬虫一直是我想要入手的方向,通过对静觅崔庆才的个人博客的学习,完成了一些小项目。在此对其及其博客表示感谢,也推荐大家学习。

本文完成的是抓取糗事百科热门段子中python爬虫代码的python 3.x版本,希望给学习过相同博文且想用python3.x完成的人带来一点启发。

具体步骤请参照抓取糗事百科热门段子,本文仅是成品。本文的正则表达式目前可用。

该项目中用到的python2.x与python3.x一些不同之处:

1.引用的模块不同,

python2.x中的urllib2在python3.x中为urllib.request

2.输出方式不同

python2.x中的print在python3.x中为print()

3.输入方式不同

[b]python2.x中的raw_input()在python3.x中为input()[/b]

4.处理异常的不同

[b]python2.x中的try:  ......[/b]

[b]except urllib2.URLError,e:    
......
[/b]

[b]在python3.x中为try: ......[/b]

[b]except urllib.request.URLError  ase: ......[/b]

#糗事百科段子爬取
# -*- coding: utf-8 -*-
import urllib.request
import re
#修改部分
import io import sys sys.stdout = io.TextIOWrapper(sys.stdout.buffer,encoding='gb18030') #改变标准输出的默认编码

#糗事百科爬虫类
class QSBK:

#初始化方法,定义变量
def __init__(self):
self.pageIndex = 1
self.user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
#初始化headers
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
request = urllib.request.Request(url,headers =self.headers)
#利用urlopen获取页面代码
response = urllib.request.urlopen(request)
#将页面转化为UTF-8编码
pageCode=response.read().decode('utf-8')
return pageCode
except urllib.request.URLError as e:
if hasattr(e,"reason"):
print(u"连接糗事百科失败,错误原因",e.reason)
return None

#传入某一页代码,返回本页不带图片的段子列表
def getPageItems(self,pageIndex):
pageCode=self.getPage(pageIndex)
if not pageCode:
print("页面加载失败....")
return None
pattern = re.compile('<div class="author clearfix">.*?title=.*?<h2>(.*?)</h2>.*?<div class="content">(.*?)</div>.*?<div class="stats">.*?class="number">(.*?)</i>.*?class="number">(.*?)</i>',re.S)
items = re.findall(pattern,pageCode)
#用来存储每页的段子们
pageStories=[]
#遍历正则表达式匹配的信息
for item in items:
text=re.sub(r'<span>|</span>'," ",item[1])
text1= re.sub(r'<br/>',"\n",text)
#item[0]是一个段子的发布者,item[1]是内容,item[2]是点赞数,item[4]是评论数
pageStories.append([item[0].strip(),text1.strip(),item[2].strip(),item[3].strip()])
return pageStories

#加载并提取页面的内容,加入到列表中
def loadPage(self):
#如果当前未看的页数少于2页,则加载新一页
if self.enable == True:
if len(self.stories) < 2:
#获取新一页
pageStories = self.getPageItems(self.pageIndex)
#将该页的段子存放到全局list中
if pageStories:
self.stories.append(pageStories)
#获取完之后页码索引加一,表示下次读取下一页
self.pageIndex += 1

#调用该方法,每次敲回车打印输出一个段子
def getOneStory(self,pageStories,page):
#遍历一页的帖子
for story in pageStories:
#等待用户输入
Input=input()
#每当输入回车一次,判断一下是否要加载新页面
self.loadPage()
#如果输入Q则程序结束
if Input=="Q":
self.enable=False
return
print(u"第%d页\t发帖人:%s\t好笑:%s\t评论:%s\n%s" %(page,story[0],story[2],story[3],story[1]))

def Start(self):
print(u"正在读取糗事百科,按回车查看新段子,Q退出")
#使变量为True,程序可以正常运行
self.enable = True
#先加载一页内容
self.loadPage()
#局部变量,控制当前读到了第几页
nowPage = 0
while self.enable:
if len(self.stories)>0:
#从全局list中获取一页的段子
pageStories = self.stories[0]
#当前读到的页数加一
nowPage += 1
#将全局list中第一个元素删除,因为已经取出
del self.stories[0]
#输出该页的段子
self.getOneStory(pageStories,nowPage)
spider=QSBK()
spider.Start()






项目效果图:
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python 爬虫 糗事百科