爬取目标:
- 爬取糗事百科上的段子
- 过滤掉有图片的段子
- 实现每敲一次回车就显示一个段子的发布人,页数,内容,发布人的性别和点赞数
一、确定所要爬取的URL并抓取当前页面
糗事百科的网址是:http://www.qiushibaike.com/hot/page/1,后面的/1是代表所浏览的页面数,所以我们可以传入一个不同的值来获取每一面的段子内容,先尝试把整个页面爬下来,代码如下
#coding:utf-8
import urllib.request
import urllib.parse
import urllib.error
from bs4 import BeautifulSoup
page = 1 #糗事百科最后一个数字代表页面
url = 'http://www.qiushibaike.com/hot/page' + str(page)
#headers验证
user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
headers = {'User-Agent' : user_agent}
print("糗事百科的段子爬取:\n")
try:
request = urllib.request.Request(url,headers=headers)
reponse = urllib.request.urlopen(request)
print(str(reponse.read(),'utf-8'))
except urllib.error.URLError as e:
if hasattr(e,"reason"):
print(e.reason)
二、提取某一页的段子
我们已经可以把一页的所有内容给爬取下来了,剩下的就是提取这一页上的段子了。
首先我们看一下网页的源码,发现,每条段子一定会包含这样的代码
<div class="article block untagged mb15" id="....">...</div>
我采用的方法是BeautifulSoup中的findAll方法来抓取每条段子,接下来,我们需要过滤掉含有图片的段子,因为带图片的段子,我还不会展示出来,经过分析,发现带图片的段子里,会包含这段代码:
<div class="thumb">...</div>
所以我们只需要查找这一段里是否有这样的标签
大略代码如下:
#coding:utf-8
import urllib.request
import urllib.parse
import urllib.error
from bs4 import BeautifulSoup
page = 2 #糗事百科最后一个数字代表页面
url = 'http://www.qiushibaike.com/hot/page' + str(page)
user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
headers = {'User-Agent' : user_agent}
print("糗事百科的段子爬取:\n")
try:
request = urllib.request.Request(url,headers=headers)
reponse = urllib.request.urlopen(request)
bsObj = BeautifulSoup(reponse.read(),'lxml')
for content in bsObj.findAll("div",{"class":"article block untagged mb15"}):
if content.find('div',{'class':'thumb'}):
continue
sex = ''
if content.find("div",{"class":"articleGender manIcon"}):#获取发布人的性别
sex = '男'
else:
sex = '女'
print("author : %s\nsex : %s" % (content.h2.get_text(),sex))
print("段子:")
article = content.find('div',{'class':'content'}).get_text()#获取发布人的昵称
i = 1
for s in article:
if i%30==0:
print('')
print(s,end="")
i+=1
print('\n')
except urllib.error.URLError as e:
if hasattr(e,"reason"):
print(e.reason)
三、完善代码
#coding:utf-8
from urllib.request import urlopen
from urllib.request import Request
from bs4 import BeautifulSoup
from urllib.error import URLError
#糗事百科类
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 = Request(url,headers=self.headers)
#利用urlopen获取页面代码
reponse = urlopen(request)
#将reponse转化为Beautiful对象
bsObj = BeautifulSoup(reponse.read(),'lxml')
return bsObj
except URLError as e:
if hasattr(e,"reason"):
print("连接糗事百科失败,错误原因 : %s" % e.reason)
return None
#传入某一页代码,返回本页不带图片的段子列表
def getPageItems(self,pageIndex):
pageCode = self.getPage(pageIndex)
if not pageCode:
print("加载页面失败......")
return None
#用来存储每页的段子
pageStories = []
sex = '' #作者性别
author = '' #作者昵称
zan = '' #段子的点赞数
items = pageCode.findAll('div',{'class':'article block untagged mb15'})
#遍历爬取的段子,摘取所需要的
for item in items:
#是否含有图片
if item.find('div',{'class':'thumb'}):
continue
# 获取所需要的基本信息
author = item.h2.get_text()
if item.find('div',{'class':'articleGender manIcon'}):
sex = '男'
else:
sex = '女'
article = item.find('div', {'class': 'content'}).get_text()
zan = item.find('span',{'class':'stats-vote'}).get_text()
tmpList = list((author,sex,article,zan))
pageStories.append(tmpList)
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:
#等待用户输入
op = input()
#每当输入回车一次,判断是否需要加载页面
self.loadPage()
#如果输入Q则程序结束
if op=='Q':
self.enable = False
return
print("第%d页\t发布人:%s(%s)" % (page,story[0],story[1]))
i = 1
for word in story[2]:
if i % 30 == 0:
print('\n')
print(word, end="")
i += 1
print('%s\n'%story[3])
#开始方法
def start(self):
print("正在读取糗事百科,按回车查看新段子,Q退出\n")
#使变量为True,程序可以正常运行
self.enable = True
#先加载一页内容
self.loadPage()
nowPage = 0
while self.enable:
if len(self.stories)>0:
#从全局list中获取一页的段子
pageStories = self.stories[0]
#当前读取页加一
nowPage += 1
del self.stories[0]
#输出该页的段子
self.getOneStory(pageStories,nowPage)
spider = QSBK()
spider.start()