python3 爬虫---爬取糗事百科
这次爬取的网站是糗事百科,网址是:http://www.qiushibaike.com/hot/page/1
分析网址,参数'page/'后面的数字''指的是页数,第二页就是'/page/2',以此类推。。。
一、分析网页

然后明确要爬取的元素:作者名、内容、好笑数、以及评论数量
每一个段子的信息存放在'div id="content-left"'下的div中

爬取元素的所在位置

二、爬取部分
工具:
Python3
requests
xpath
1、获取每一个段子
# 返回页面的div_list
def getHtmlDivList(self, pageIndex):
pageUrl = 'http://www.qiushibaike.com/hot/page/' + str(pageIndex)
html = requests.get(url=pageUrl, headers=self.headers).text
selector = etree.HTML(html)
divList = selector.xpath('//div[@id="content-left"]/div')
return divList
每一个段子都在div中,这里用xpath,筛选出来后返回的是一个列表,每一个div都在里面
2、获取每一个段子中的元素
def getHtmlItems(self, divList):
items = []
for div in divList:
item = []
# 发布人
name = div.xpath('.//h2/text()')[0].replace("\n", "")
item.append(name)
# 内容(阅读全文)
contentForAll = div.xpath('.//div[@class="content"]/span[@class="contentForAll"]')
if contentForAll:
contentForAllHref = div.xpath('.//a[@class="contentHerf"]/@href')[0]
contentForAllHref = "https://www.qiushibaike.com" + contentForAllHref
contentForAllHrefPage = requests.get(url=contentForAllHref).text
selector2 = etree.HTML(contentForAllHrefPage)
content = selector2.xpath('//div[@class="content"]/text()')
content = "".join(content)
content = content.replace("\n", "")
else:
content = div.xpath('.//div[@class="content"]/span/text()')
content = "".join(content)
content = content.replace("\n", "")
item.append(content)
# 点赞数
love = div.xpath('.//span[@class="stats-vote"]/i[@class="number"]/text()')
love = love[0]
item.append(love)
# 评论人数
num = div.xpath('.//span[@class="stats-comments"]//i[@class="number"]/text()')
num = num[0]
item.append(num)
items.append(item)
return items
这里需要注意的是,xpath返回的是一个列表,筛选出来后需要用[0]获取到字符串类型
上面的代码中,爬取的内容里,有的段子是这样的,如下图: 
内容中会有标签<br>,那么用xpath爬取出来后,里面的内容都会成一个列表(这里的div就是列表),
那div[0]就是"有一次回老家看姥姥,遇到舅妈说到表弟小时候的事~",所以需要将div转换成字符串
其他的部分就xpath语法的使用
3、保存进文本
# 保存入文本
def saveItem(self, items):
f = open('F:\\Pythontest1\\qiushi.txt', "a", encoding='UTF-8') for item in items:
name = item[0]
content = item[1]
love = item[2]
num = item[3] # 写入文本
f.write("发布人:" + name + '\n')
f.write("内容:" + content + '\n')
f.write("点赞数:" + love + '\t')
f.write("评论人数:" + num)
f.write('\n\n') f.close()
4、全部代码
import os
import re
import requests
from lxml import etree # 糗事百科爬虫
class QSBK:
# 初始化方法,定义变量
def __init__(self):
self.pageIndex = 1
self.headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.86 Safari/537.36"
}
self.enable = False # 返回页面的div_list
def getHtmlDivList(self, pageIndex):
pageUrl = 'http://www.qiushibaike.com/hot/page/' + str(pageIndex)
html = requests.get(url=pageUrl, headers=self.headers).text
selector = etree.HTML(html)
divList = selector.xpath('//div[@id="content-left"]/div')
return divList # 获取文本中要截取的元素
def getHtmlItems(self, divList): items = [] for div in divList:
item = []
# 发布人
name = div.xpath('.//h2/text()')[0].replace("\n", "")
item.append(name) # 内容(阅读全文)
contentForAll = div.xpath('.//div[@class="content"]/span[@class="contentForAll"]')
if contentForAll:
contentForAllHref = div.xpath('.//a[@class="contentHerf"]/@href')[0]
contentForAllHref = "https://www.qiushibaike.com" + contentForAllHref
contentForAllHrefPage = requests.get(url=contentForAllHref).text
selector2 = etree.HTML(contentForAllHrefPage)
content = selector2.xpath('//div[@class="content"]/text()')
content = "".join(content)
content = content.replace("\n", "")
else:
content = div.xpath('.//div[@class="content"]/span/text()')
content = "".join(content)
content = content.replace("\n", "")
item.append(content) # 点赞数
love = div.xpath('.//span[@class="stats-vote"]/i[@class="number"]/text()')
love = love[0]
item.append(love) # 评论人数
num = div.xpath('.//span[@class="stats-comments"]//i[@class="number"]/text()')
num = num[0]
item.append(num) items.append(item) return items # 保存入文本
def saveItem(self, items):
f = open('F:\\Pythontest1\\qiushi.txt', "a", encoding='UTF-8') for item in items:
name = item[0]
content = item[1]
love = item[2]
num = item[3] # 写入文本
f.write("发布人:" + name + '\n')
f.write("内容:" + content + '\n')
f.write("点赞数:" + love + '\t')
f.write("评论人数:" + num)
f.write('\n\n') f.close() # 判断文本是否已创建,添加路径
def judgePath(self):
if os.path.exists('F:\\Pythontest1') == False:
os.mkdir('F:\\Pythontest1')
if os.path.exists("F:\\Pythontest1\\qiushi.txt") == True:
os.remove("F:\\Pythontest1\\qiushi.txt") def start(self):
self.judgePath()
print("正在读取糗事百科,按回车继续保存下一页,Q退出")
self.enable = True
while self.enable:
divList = self.getHtmlDivList(self.pageIndex)
data = self.getHtmlItems(divList)
self.saveItem(data)
print('已保存第%d页的内容' % self.pageIndex)
pan = input('是否继续保存:')
if pan != 'Q':
self.pageIndex += 1
self.enable = True
else:
print('程序运行结束!!')
self.enable = False spider = QSBK()
spider.start()
python3 爬虫---爬取糗事百科的更多相关文章
- python学习(十六)写爬虫爬取糗事百科段子
原文链接:爬取糗事百科段子 利用前面学到的文件.正则表达式.urllib的知识,综合运用,爬取糗事百科的段子先用urllib库获取糗事百科热帖第一页的数据.并打开文件进行保存,正好可以熟悉一下之前学过 ...
- Python爬虫爬取糗事百科段子内容
参照网上的教程再做修改,抓取糗事百科段子(去除图片),详情见下面源码: #coding=utf-8#!/usr/bin/pythonimport urllibimport urllib2import ...
- Python爬虫-爬取糗事百科段子
闲来无事,学学python爬虫. 在正式学爬虫前,简单学习了下HTML和CSS,了解了网页的基本结构后,更加快速入门. 1.获取糗事百科url http://www.qiushibaike.com/h ...
- python爬虫之爬取糗事百科并将爬取内容保存至Excel中
本篇博文为使用python爬虫爬取糗事百科content并将爬取内容存入excel中保存·. 实验环境:Windows10 代码编辑工具:pycharm 使用selenium(自动化测试工具)+p ...
- python_爬虫一之爬取糗事百科上的段子
目标 抓取糗事百科上的段子 实现每按一次回车显示一个段子 输入想要看的页数,按 'Q' 或者 'q' 退出 实现思路 目标网址:糗事百科 使用requests抓取页面 requests官方教程 使用 ...
- 8.Python爬虫实战一之爬取糗事百科段子
大家好,前面入门已经说了那么多基础知识了,下面我们做几个实战项目来挑战一下吧.那么这次为大家带来,Python爬取糗事百科的小段子的例子. 首先,糗事百科大家都听说过吧?糗友们发的搞笑的段子一抓一大把 ...
- python网络爬虫--简单爬取糗事百科
刚开始学习python爬虫,写了一个简单python程序爬取糗事百科. 具体步骤是这样的:首先查看糗事百科的url:http://www.qiushibaike.com/8hr/page/2/?s=4 ...
- Python爬虫实战一之爬取糗事百科段子
大家好,前面入门已经说了那么多基础知识了,下面我们做几个实战项目来挑战一下吧.那么这次为大家带来,Python爬取糗事百科的小段子的例子. 首先,糗事百科大家都听说过吧?糗友们发的搞笑的段子一抓一大把 ...
- 转 Python爬虫实战一之爬取糗事百科段子
静觅 » Python爬虫实战一之爬取糗事百科段子 首先,糗事百科大家都听说过吧?糗友们发的搞笑的段子一抓一大把,这次我们尝试一下用爬虫把他们抓取下来. 友情提示 糗事百科在前一段时间进行了改版,导致 ...
随机推荐
- hbase建表
import java.util.ArrayList; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hb ...
- shell命令输入输出重定向
Linux命令的执行过程 首先是输入:stdin输入可以从键盘,也可以从文件得到 命令执行完成:把成功结果输出到屏幕,stout默认是屏幕 命令执行有错误:把错误也输出到屏幕上面,stderr默认也是 ...
- ionic3 打包安卓平台环境搭建报错解决方案总结
1.jvm虚拟机提供的运行空间小于项目所需的空间是报错.如图: 解决方法:在环境变量中配置jvm的运行内存大小,大于所需的内存即可. 其中:-Xmx512M可根据实际提示情况,进行更改,如1024M, ...
- asp.net应用发布到IIS无法链接到oracle数据库
遇到这个问题纠结了好久,试了好多的方法,其中我的问题是,先安装了.net frameword4然后又安装的IIS. 正确方式应该是先安装IIS 然后安装.net framework;且应用程序池没有启 ...
- Java多线程由易到难
线程可以驱动任务,因此你需要一种描述任务的方式,这可以由Runnable接口来提供.要想定义任务,只需实现Runnable接口并编写run方法,使得该任务可以执行你的命令. public class ...
- Android Imageview 图片居左居右,自定义圆角
android:scaleType="fitStart" 图片靠左不变形显示, android:scaleType=”fitEnd” 图片靠右显示,不变形. 半透明andr ...
- 简述Handler机制
我会对android的消息处理有三个核心类逐步介绍,他们分别是:Looper,Handler和Message.其实还有一Message Queue(消息队列),知道它是队列即可,就像我们所熟知的数组, ...
- web离线应用--applicationCache
applicationCache是html5新增的一个离线应用功能 离线浏览: 用户可以在离线状态下浏览网站内容. 更快的速度: 因为数据被存储在本地,所以速度会更快. 减轻服务器的负载: 浏览器只会 ...
- fragment显示 Binary XML file line #12: Error inflating class fragment 错误
问题 最近换了新机子,今天在静态用fragment时突然发现闪退,一看显示 Binary XML file line #12: Error inflating class fragment 错误 后面 ...
- Python简单爬虫
爬虫简介 自动抓取互联网信息的程序 从一个词条的URL访问到所有相关词条的URL,并提取出有价值的数据 价值:互联网的数据为我所用 简单爬虫架构 实现爬虫,需要从以下几个方面考虑 爬虫调度端:启动爬虫 ...