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>
金失&金华…
</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 time
class 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].text
else:
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
# 定义字典存mongo
d = {
"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.text
self.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 re
headers = {"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.text
duanzi = 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)
# 定义字典存mongo
d = {
"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 requests
class ThreadCrawl(threading.Thread):
'''
定义爬取网页处理类,从页码队列中取出页面,拼接url,请求数据,并把数据存到数据队列中
'''
def __init__(self, threadName, pageQueue, dataQueue):
'''
构造函数
:param threadName:当前线程名称
:param pageQueue: 页面队列
:param dataQueue: 数据队列
'''
super(ThreadCrawl, self).__init__()
self.threadName = threadName
self.pageQueue = pageQueue
self.dataQueue = dataQueue
self.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).text
self.dataQueue.put(content)
print(self.threadName + '爬取数据')
except:
pass
# 解析线程是否结束的标识
PARSE_THREAD_EXIST = False
class ParseThread(threading.Thread):
'''
网页数据解析类
'''
def __init__(self,threadName,dataQueue,fileName):
'''
解析线程的构造函数
:param threadName:当前线程名称
:param dataQueue:数据队列
:param fileName:文件名
'''
super(ParseThread,self).__init__()
self.threadName = threadName
self.dataQueue = dataQueue
self.fileName = fileName
def 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:
pass
def 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()
# 判断数据队列中是否处理完成了,当处理完成后,将退出解析线程标识为True
if pageQueue.empty():
global PARSE_THREAD_EXIST
PARSE_THREAD_EXIST = True
# 等待解析线程退出
for thread in parseThreadList:
thread.join()
if __name__ == "__main__":
main()