Python爬虫学习笔记 -- 爬取糗事百科

代码存放地址: https://github.com/xyls2011/python/tree/master/qiushibaike
爬取网址:https://www.qiushibaike.com/text/

知识点:xpath用法,requests, etree, pymongo,多线程threading

文章概览:
1)介绍了xpath的用法;
2)将xpath具体运用到爬取糗事百科段子;
3)进一步对比分析了单线程爬取和多线程爬取的效率。

参考文章:https://blog.csdn.net/u013332124/article/details/80621638

1、xpath的用法

一、xpath介绍

XPath 是一门在 XML 文档中查找信息的语言。XPath 用于在 XML 文档中通过元素和属性进行导航。

  • XPath 使用路径表达式在 XML 文档中进行导航
  • XPath 包含一个标准函数库
  • XPath 是 XSLT 中的主要元素
  • XPath 是一个 W3C 标准

节点

在 XPath 中,有七种类型的节点:元素、属性、文本、命名空间、处理指令、注释以及文档(根)节点。XML 文档是被作为节点树来对待的。

二、xpath语法

表达式 描述
nodename 选取此节点的所有子节点。
/ 从根节点选取。
// 从匹配选择的当前节点选择文档中的节点,而不考虑它们的位置。
. 选取当前节点。
.. 选取当前节点的父节点。
@ 选取属性。

例子

以下面这个xml为例子

<?xml version="1.0" encoding="ISO-8859-1"?><bookstore><book><title lang="eng">Harry Potter</title><price>29.99</price>
</book><book><title lang="eng">Learning XML</title><price>39.95</price>
</book></bookstore>
  • xml.xpath(“bookstore”) 表示选取 bookstore 元素的所有子节点
  • xml.xpath(“/bookstore”) 表示选取根元素 bookstore。
  • xml.xpath(“bookstore/book”) 选取属于 bookstore 的子元素的所有 book 元素。
  • xml.xpath(“//book”) 选取所有 book 子元素,而不管它们在文档中的位置。
  • xml.xpath(“bookstore//book”) 选择属于 bookstore 元素的后代的所有 book 元素,而不管它们位于 bookstore 之下的什么位置。
  • xml.xpath(“//@lang”) 选取名为 lang 的所有属性。

谓语

路径表达式 结果
/bookstore/book[1] 选取属于 bookstore 子元素的第一个 book 元素。
/bookstore/book[last()] 选取属于 bookstore 子元素的最后一个 book 元素。
/bookstore/book[last()-1] 选取属于 bookstore 子元素的倒数第二个 book 元素。
/bookstore/book[position()<3] 选取最前面的两个属于 bookstore 元素的子元素的 book 元素。
//title[@lang] 选取所有拥有名为 lang 的属性的 title 元素。
//title[@lang=’eng’] 选取所有 title 元素,且这些元素拥有值为 eng 的 lang 属性。
/bookstore/book[price>35.00] 选取 bookstore 元素的所有 book 元素,且其中的 price 元素的值须大于 35.00。
/bookstore/book[price>35.00]/title 选取 bookstore 元素中的 book 元素的所有 title 元素,且其中的 price 元素的值须大于 35.00。

选取未知节点

通配符 描述
* 匹配任何元素节点。
@* 匹配任何属性节点。
node() 匹配任何类型的节点。

例子:

路径表达式 结果
/bookstore/* 选取 bookstore 元素的所有子元素。
//* 选取文档中的所有元素。
//title[@*] 选取所有带有属性的 title 元素。

选取若干路径

通过在路径表达式中使用“|”运算符,您可以选取若干个路径。

  • //book/title | //book/price 选取 book 元素的所有 title 和 price 元素。
  • //title | //price 选取文档中的所有 title 和 price 元素。
  • /bookstore/book/title | //price 选取属于 bookstore 元素的 book 元素的所有 title 元素,以及文档中所有的 price 元素。

三、轴

轴可定义相对于当前节点的节点集。

轴名称 结果
ancestor 选取当前节点的所有先辈(父、祖父等)。
ancestor-or-self 选取当前节点的所有先辈(父、祖父等)以及当前节点本身。
attribute 选取当前节点的所有属性。
child 选取当前节点的所有子元素。
descendant 选取当前节点的所有后代元素(子、孙等)。
descendant-or-self 选取当前节点的所有后代元素(子、孙等)以及当前节点本身。
following 选取文档中当前节点的结束标签之后的所有节点。
namespace 选取当前节点的所有命名空间节点。
parent 选取当前节点的父节点。
preceding 选取文档中当前节点的开始标签之前的所有节点。
preceding-sibling 选取当前节点之前的所有同级节点。
self 选取当前节点。

步的语法:
轴名称::节点测试[谓语]

例子:

例子 结果
child::book 选取所有属于当前节点的子元素的 book 节点。
attribute::lang 选取当前节点的 lang 属性。
child::* 选取当前节点的所有子元素。
attribute::* 选取当前节点的所有属性。
child::text() 选取当前节点的所有文本子节点。
child::node() 选取当前节点的所有子节点。
descendant::book 选取当前节点的所有 book 后代。
ancestor::book 选择当前节点的所有 book 先辈。
ancestor-or-self::book 选取当前节点的所有 book 先辈以及当前节点(如果此节点是 book 节点)
child::*/child::price 选取当前节点的所有 price 孙节点。

四、一些函数

1). starts-with函数

获取以xxx开头的元素
例子:xpath(‘//div[stars-with(@class,”test”)]’)

2) contains函数

获取包含xxx的元素
例子:xpath(‘//div[contains(@id,”test”)]’)

3) and

与的关系
例子:xpath(‘//div[contains(@id,”test”) and contains(@id,”title”)]’)

4) text()函数

例子1:xpath(‘//div[contains(text(),”test”)]’)
例子2:xpath(‘//div[@id=”“test]/text()’)

2、用xpath爬取糗事百科段子,并存入MongoDB

参考文章:https://blog.csdn.net/qq_41866851/article/details/85340884 文档结构分析

<div class="article block untagged mb15 typs_long" id='qiushi_tag_121891020'><div class="author clearfix">
<a href="/users/31993911/" target="_blank" rel="nofollow" style="height: 35px" onclick="_hmt.push(['_trackEvent','web-list-author-img','chick'])"><img src="//pic.qiushibaike.com/system/avtnew/3199/31993911/thumb/20190606190040.jpg?imageView2/1/w/90/h/90" alt="金失&金华">
</a>
<a href="/users/31993911/" target="_blank" onclick="_hmt.push(['_trackEvent','web-list-author-text','chick'])">
<h2>
金失&amp;金华…
</h2>
</a>
<div class="articleGender manIcon">34</div>
</div><a href="/article/121891020" target="_blank" class="contentHerf" onclick="_hmt.push(['_trackEvent','web-list-content','chick'])">
<div class="content">
<span>早上起晚了,匆匆忙忙去上班,刚出小区门口,正赶上邻居李姐提着早点要进来,她一边笑一边冲我打招呼,完全没注意到后面来了一辆汽车……<br/>小区的升降门一下子就起来了,一下怼到她下巴上,疼得她下意识伸手去挡,装包子的塑料袋瞬间掉到了她脚面上,豆腐脑一点也没浪费,全洒在了她的白t恤上,烫的她龇牙咧嘴,豆腐脑里的香菜叶在她胸..前微微摇晃着……<br/>我连忙上去帮忙,想把菜叶拿掉,一着急,踩到了路上撒的豆腐脑,这才一个趔趄撞到了李姐,手也不受控制的按在了李姐的胸.前………
…
</span><span class="contentForAll">查看全文</span></div>
</a>
<!-- 图片或gif --><div class="stats">
<!-- 笑脸、评论数等 --><span class="stats-vote"><i class="number">692</i> 好笑</span>
<span class="stats-comments">
<span class="dash"> · </span>
<a href="/article/121891020" data-share="/article/121891020" id="c-121891020" class="qiushi_comments" target="_blank" onclick="_hmt.push(['_trackEvent','web-list-comment','chick'])">
<i class="number">17</i> 评论
</a>
</span>
</div>

具体代码:

import requests
from lxml import etree
import pymongo
import timeclass QiushiSpider:def __init__(self):self.headers = {"User-Agent": "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0)"}# 链接对象self.conn = pymongo.MongoClient("localhost", 27017)# 库对象self.db = self.conn["Qiushi_DB1"]# 集合对象self.myset = self.db["duanzi"]# 解析并写入数据库def parsePage(self, html):parseHtml = etree.HTML(html)# 基准XPath,每个段子对象baseList = parseHtml.xpath('//div[contains(@id,"qiushi_tag_")]')# for循环遍历每个段子对象,1个1个提取for base in baseList:# base : <element at ...># 用户昵称username = base.xpath('./div/a/h2')if username:username = username[0].textelse:username = "匿名用户"# 段子内容content = base.xpath('./a/div[@class="content"]/span/text()')content = "".join(content).strip()# 好笑数量laughNum = base.xpath('.//i[@class="number"]')[0].text# 评论数量commentsNum = base.xpath('.//i[@class="number"]')[1].text# 定义字典存mongod = {"username": username.strip(),"content": content.strip(),"laughNum": laughNum,"commentsNum": commentsNum}self.myset.insert_one(d)# 获取页面def getPage(self, url):response = requests.get(url, headers=self.headers)# response.enconding = "utf-8"html = response.textself.parsePage(html)def workOn(self):for page in range(1, 21):url = 'https://www.qiushibaike.com/text/page/' + str(page)+'/'print('正在爬取url:', url)self.getPage(url)time.sleep(2)if __name__ == "__main__":print("start crawling qiushibaike:")spider = QiushiSpider()spider.workOn()

正则爬取版本:

import requests
from lxml import etree
import pymongo
import time
import reheaders = {"User-Agent": "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0)"}
conn = pymongo.MongoClient("localhost", 27017)
db = conn["qs_db"]
myset = db["qs_duanzi"]
base_url = 'https://www.qiushibaike.com/text/page/'for page in range(1, 21):url = base_url + str(page) + '/'print(url)response = requests.get(url, headers=headers)html = response.textduanzi = re.findall(r'<div class="article block untagged mb15.*?<img src="//(.*?)" alt=.*?<h2>(.*?)</h2>.*?<span>(.*?)</span>.*?<i class="number">(.*?)</i> 好笑</span>.*?<i class="number">(.*?)</i> 评论',html,re.S)print(len(duanzi))for i in range(0, len(duanzi)):user_icon_link, user_name, joke_content, like_num, comment_num = duanzi[i]print(user_icon_link, user_name, joke_content, like_num, comment_num)# 定义字典存mongod = {"user_icon_link": user_icon_link,"user_name": user_name.strip(),"joke_content": joke_content.strip(),"like_num": like_num,"comment_num": comment_num}myset.insert_one(d)print('爬取第%s页完毕,将要休眠2秒钟后继续爬取'%page)time.sleep(2)

3、对比分析单线程爬取和多线程爬取的效率

参考文章:https://www.cnblogs.com/toloy/p/8625328.html

# 导入队列包
import queue
# 导入线程包
import threading
# 导入json处理包
import json
# import pymongo
# 导入xpath处理包
from lxml import etree
# 导入请求处理包
import requestsclass ThreadCrawl(threading.Thread):'''定义爬取网页处理类,从页码队列中取出页面,拼接url,请求数据,并把数据存到数据队列中'''def __init__(self, threadName, pageQueue, dataQueue):'''构造函数:param threadName:当前线程名称:param pageQueue: 页面队列:param dataQueue: 数据队列'''super(ThreadCrawl, self).__init__()self.threadName = threadNameself.pageQueue = pageQueueself.dataQueue = dataQueueself.headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.186 Safari/537.36"}def run(self):'''线程执行的run方法:return:'''while not self.pageQueue.empty():try:pageNum = self.pageQueue.get(False)url = "http://www.dfenqi.cn/Product/Category?category=4945805937081335060-0-0&pageIndex=" + str(pageNum)content = requests.get(url,headers = self.headers).textself.dataQueue.put(content)print(self.threadName + '爬取数据')except:pass# 解析线程是否结束的标识
PARSE_THREAD_EXIST = Falseclass ParseThread(threading.Thread):'''网页数据解析类'''def __init__(self,threadName,dataQueue,fileName):'''解析线程的构造函数:param threadName:当前线程名称:param dataQueue:数据队列:param fileName:文件名'''super(ParseThread,self).__init__()self.threadName = threadNameself.dataQueue = dataQueueself.fileName = fileNamedef run(self):'''解析线程的执行run方法,从数据队列取出数据,解析数据,再存入到本地文件中:return:'''while not PARSE_THREAD_EXIST:try:html = self.dataQueue.get(False)print(self.threadName + '取到数据')text = etree.HTML(html)# 解析网页中的数据,此处可根据需要,定制解析方法或解析类来实现titleList = text.xpath("//div[@class='liebiao']/ul/li/a/p/text()")with open(self.fileName,'a',encoding='utf-8') as f:for title in titleList:f.write(title + "\n")print(self.threadName + '解析完成')except:passdef main():'''调度方法,main入口执行方法:return:'''# 创建页码队列,用于存储页码pageQueue = queue.Queue(50)for i in range(1, 51):pageQueue.put(i)# 数据队列,用于存储爬取的数据供解析线程使用dataQueue = queue.Queue()# 将解析结果保存的文件名fileName = 'file.txt'# 爬取线程的名称列表cawlThreadNameList = ['线程一', '线程二']crawThreadlList = []for threadName in cawlThreadNameList:thread = ThreadCrawl(threadName, pageQueue, dataQueue)thread.start()crawThreadlList.append(thread)# 解析线程的名称列表parseThreadNameList = ['解析线程一','解析线程二']parseThreadList = []for threadName in parseThreadNameList:thread = ParseThread(threadName,dataQueue,fileName)thread.start()parseThreadList.append(thread)# 等待爬取线程处理结束for thread in crawThreadlList:thread.join()# 判断数据队列中是否处理完成了,当处理完成后,将退出解析线程标识为Trueif pageQueue.empty():global PARSE_THREAD_EXISTPARSE_THREAD_EXIST = True# 等待解析线程退出for thread in parseThreadList:thread.join()if __name__ == "__main__":main()

Python爬虫学习笔记 -- 爬取糗事百科相关推荐

  1. Python爬虫实战之爬取糗事百科段子

    Python爬虫实战之爬取糗事百科段子 完整代码地址:Python爬虫实战之爬取糗事百科段子 程序代码详解: Spider1-qiushibaike.py:爬取糗事百科的8小时最新页的段子.包含的信息 ...

  2. python 爬虫实战1 爬取糗事百科段子

    首先,糗事百科大家都听说过吧?糗友们发的搞笑的段子一抓一大把,这次我们尝试一下用爬虫把他们抓取下来. 本篇目标 抓取糗事百科热门段子 过滤带有图片的段子 实现每按一次回车显示一个段子的发布时间,发布人 ...

  3. Python爬虫练习:爬取糗事百科

    本文的文字及图片来源于网络,仅供学习.交流使用,不具有任何商业用途,版权归原作者所有,如有问题请及时联系我们以作处理 以下文章来源于CSDN,作者不温卜火 爬取前的准备 糗事百科官网:https:// ...

  4. python爬虫——利用BeautifulSoup4爬取糗事百科的段子

    1 import requests 2 from bs4 import BeautifulSoup as bs 3 4 #获取单个页面的源代码网页 5 def gethtml(pagenum): 6 ...

  5. 爬虫第四战爬取糗事百科搞笑段子

    又开始了新的篇章,本熊继续一个Python小白的修行之路,这次要爬取糗事百科主页的段子,恩 ..看起来不错的样子,只是段子不能吃 ,不然,啧啧... 相信很多人有去糗百看段子减压的习惯,如果能把这些段 ...

  6. python爬虫经典段子_Python爬虫实战之爬取糗事百科段子

    首先,糗事百科大家都听说过吧?糗友们发的搞笑的段子一抓一大把,这次我们尝试一下用爬虫把他们抓取下来. 友情提示 糗事百科在前一段时间进行了改版,导致之前的代码没法用了,会导致无法输出和CPU占用过高的 ...

  7. 【资料下载】Python 第三讲——正则表达式爬取糗事百科数据...

    直播时间:2月20日 20:00-21:00 直播讲师:罗攀--林学研究生<从零开始学Python网络爬虫>作者 <从零开始学Python数据分析>作者.擅长网络爬虫.数据分析 ...

  8. Python使用aiohttp异步爬取糗事百科

    from bs4 import BeautifulSoup import aiohttp # 代替requests import asyncio from urllib import parsehea ...

  9. python爬虫爬取糗事百科

    最近研究python爬虫,按照网上资料实现了python爬虫爬取糗事百科,做个笔记. 分享几个学习python爬虫资料: 廖雪峰python教程 主要讲解python的基础编程知识 python开发简 ...

最新文章

  1. PCB的EMC设计之PCB叠层结构
  2. 澄清大数据存储——系统集成商篇
  3. linux 天堂测试软件,[Ubuntu] HTTP Live Streaming 安装测试
  4. C# 线程知识--使用Task执行异步操作(转)
  5. mongodb性能分析方法:explain()
  6. 如何给 SAP Fiori Elements 应用的字段添加 value help
  7. 2021苏州大学计算机考研分数,苏州大学2021考研分数线已公布
  8. linux添加删除回环地址,CentOS7如何添加本地回环地址?CentOS7添加本地回环地址的方法...
  9. 简单的识别猫狗的模型
  10. 通云之路 从虚拟化迈向企业私有云
  11. Sklearn-RandomForest
  12. 05.日志框架与Spring Boot日志全篇
  13. HowNet介绍及相关API的使用方法
  14. 蓝桥杯省赛JavaB组真题
  15. 2019牛客多校赛第8场 D Distance 三维树状数组
  16. 计算机windows10怎么找word,Win10 word路径在哪?Win10如何修改word路径
  17. SIM卡中ICCID标识与IMSI的区别
  18. 使用markman助力移动应用开发
  19. C#学习(二十五)——如何在PictureBox上画十字架
  20. 如何保障云上数据安全?一文详解云原生全链路加密

热门文章

  1. C/C++ 之 操作符重载
  2. java分割图片_OpenCV3 Java分割图像 提取图像的RGB三原色(Core.split)
  3. 饭店餐饮点餐系统为什么这么受欢迎?
  4. C++简单程序典型案例
  5. etf持仓和现货黄金走势有多大关系?
  6. 英国哪些大学本科可以用ib English hl 成绩代替雅思成绩?
  7. ARCGIS与QGIS对比,WEBGIS所用到的软件
  8. 白盒测试(单元测试JUnit使用断言assertThat中startsWith、endsWith方法)
  9. 自动控制理论的发展历程
  10. NoHttp的学习使用