在别人博客里学习的 抓取糗百段子,由于糗百不断的更新,代码需要改正。

抓取网页:http://www.qiushibaike.com/hot/page/1

修改后的代码如下:

# -*- coding:utf-8 -*-

import urllib
import urllib2
import re
import thread
import time #糗事百科爬虫类
class QSBK: #初始化方法,定义一些变量
def __init__(self):
self.pageIndex = 1
#user_agent 从火狐 HttpFox中headers查找到
#self.user_agent = 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:45.0)'
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 = urllib2.Request(url,headers = self.headers)
#利用urlopen获取页面代码
response = urllib2.urlopen(request)
#将页面转化为UTF-8编码
pageCode = response.read().decode('utf-8')
return pageCode except urllib2.URLError, 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">.*?href.*?<img src.*?title=.*?<h2>(.*?)</h2>.*?<div class="content">(.*?)</div>.*?<i class="number">(.*?)</i>',re.S)
items = re.findall(pattern,pageCode)
#print len(items)
#print "*****items"
#用来存储每页的段子们
pageStories = []
#遍历正则表达式匹配的信息
i = 0
for item in items:
#如果不含有图片,把它加入list中
#if not haveImg:
replaceBR = re.compile('<.?span>')
#将<br/> 用 换行符\n 替换
text = re.sub(replaceBR,"\n",item[1])
#item[0]是一个段子的发布者,item[1]是内容,item[2]是发布时间,item[4]是点赞数
pageStories.append([item[0],text,item[2]]) #strip()作用:去掉转义字符后输出
#print item[0] +"-------0t"
#print item[1] +"-------0T"
#print text + "******TEXT"
#print item[2] +"-------0t" 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 print len(self.stories)
#调用该方法,每次敲回车打印输出一个段子
def getOneStory(self,pageStories,page):
#遍历一页的段子 for story in pageStories:
#等待用户输入
input = raw_input()
#每当输入回车一次,判断一下是否要加载新页面
self.loadPage()
#如果输入Q则程序结束
if input == "Q":
self.enable = False
return
#print "$$$"
print len(story)
#现在网页已没有发布时间了
#print u"第%d页\t发布人:%s\t发布时间:%s\t赞:%s\n%s" %(page,story[0],story[2],story[3],story[1])
print u"第%d页\t发布人:%s\t赞:%s\n%s" %(page,story[0],story[2],story[1]) #开始方法
def start(self):
print u"正在读取糗事百科,按回车查看新段子,Q退出"
#使变量为True,程序可以正常运行
self.enable = True #先加载一页内容
self.loadPage() #局部变量,控制当前读到了第几页
nowPage = 0
while self.enable:
if len(self.stories)>0:
#print len(self.stories)
#print "-------stories"
#从全局list中获取一页的段子
pageStories = self.stories[0]
#当前读到的页数加一
nowPage += 1
#将全局list中第一个元素删除,因为已经取出
del self.stories[0]
#print "---------------------------------"
#print len(pageStories)
#print nowPage
#输出该页的段子
self.getOneStory(pageStories,nowPage) spider = QSBK()
spider.start()

Python爬虫——抓取糗百段子的更多相关文章

  1. Python爬虫抓取糗百的图片,并存储在本地文件夹

    思路: 1.观察网页,找到img标签 2.通过requests和BS库来提取网页中的img标签 3.抓取img标签后,再把里面的src给提取出来,接下来就可以下载图片了 4.通过urllib的urll ...

  2. python 爬虫抓取心得

    quanwei9958 转自 python 爬虫抓取心得分享 urllib.quote('要编码的字符串') 如果你要在url请求里面放入中文,对相应的中文进行编码的话,可以用: urllib.quo ...

  3. Python爬虫----抓取豆瓣电影Top250

    有了上次利用python爬虫抓取糗事百科的经验,这次自己动手写了个爬虫抓取豆瓣电影Top250的简要信息. 1.观察url 首先观察一下网址的结构 http://movie.douban.com/to ...

  4. Python爬虫抓取东方财富网股票数据并实现MySQL数据库存储

    Python爬虫可以说是好玩又好用了.现想利用Python爬取网页股票数据保存到本地csv数据文件中,同时想把股票数据保存到MySQL数据库中.需求有了,剩下的就是实现了. 在开始之前,保证已经安装好 ...

  5. python爬虫抓取哈尔滨天气信息(静态爬虫)

    python 爬虫 爬取哈尔滨天气信息 - http://www.weather.com.cn/weather/101050101.shtml 环境: windows7 python3.4(pip i ...

  6. Python爬虫--抓取糗事百科段子

    今天使用python爬虫实现了自动抓取糗事百科的段子,因为糗事百科不需要登录,抓取比较简单.程序每按一次回车输出一条段子,代码参考了 http://cuiqingcai.com/990.html 但该 ...

  7. Python爬虫 -- 抓取电影天堂8分以上电影

    看了几天的python语法,还是应该写个东西练练手.刚好假期里面看电影,找不到很好的影片,于是有个想法,何不搞个爬虫把电影天堂里面8分以上的电影爬出来.做完花了两三个小时,撸了这么一个程序.反正蛮简单 ...

  8. Python 爬虫: 抓取花瓣网图片

    接触Python也好长时间了,一直没什么机会使用,没有机会那就自己创造机会!呐,就先从爬虫开始吧,抓点美女图片下来. 废话不多说了,讲讲我是怎么做的. 1. 分析网站 想要下载图片,只要知道图片的地址 ...

  9. python爬虫 抓取一个网站的所有网址链接

    sklearn实战-乳腺癌细胞数据挖掘 https://study.163.com/course/introduction.htm?courseId=1005269003&utm_campai ...

随机推荐

  1. Implement Insert and Delete of Tri-nay Tree

    问题 Implement insert and delete in a tri-nary tree. A tri-nary tree is much like a binary tree but wi ...

  2. jquery实现简单鼠标经过图片预览效果

    html结构:<div class="prebtn"><img src=""/></div> css代码:#preview{ ...

  3. Matlab 图像预处理

    %%%%%%%%%%%%%%%%% %%降采样 clear all im={}; %创建字典保存读取的图片 dis=dir('F:\kaggle_data_zip\Sample\*.jpeg');%% ...

  4. cf D. Levko and Array

    http://codeforces.com/contest/361/problem/D 用二分搜索相邻两个数的差的绝对值,然后用dp记录数改变的次数.dp[i]表示在i之前改变的次数,如果|a[i]- ...

  5. 2015必须推荐的Android框架,猿必读系列!

    一.Guava Google 的基于java1.6的类库集合的扩展项目,包括collections, caching, primitives support, concurrency librarie ...

  6. (1) 一个字符串,根据输入参数m,找出字符串的m个字符的所有字符串

    /** * 有一个字符串,根据输入参数m,找出字符串的m个字符的所有字符串 例如: String str ="abc", m=2 得到结果是 "ab" &quo ...

  7. 把第三方的exe程序嵌入C#界面上

    public partial class eTerm_Form : WinFormsUI.Docking.DockContent{public eTerm_Form(){InitializeCompo ...

  8. poj1185:炮兵阵地(状压dp)

    也算是比较基础的状压dp了,跟做过的第二道比较又稍微复杂了一点 需要记录之前两行的状态.. 统计结果也稍有不同 另外还学习了一个得到一个整数二进制位 1 的个数的位运算方法 详见代码: #includ ...

  9. openStack kilo 手动Manual部署随笔记录

    一 ,基于neutron网络资源主机(控制节点,网络节点,计算节点)网络规划配置 1, controller.cc 节点 网络配置截图

  10. HDU 4444 Walk (离散化建图+BFS+记忆化搜索) 绝对经典

    题目地址:http://acm.hdu.edu.cn/showproblem.php?pid=4444 题意:给你一些n个矩形,给你一个起点,一个终点,要你求从起点到终点最少需要转多少个弯 题解:因为 ...