利用xpath爬取糗事百科的数据,关键在于对xpath的使用,可以用浏览器插件对xpath做相应的对照。
我的处理方法是提取出来相对比较有“概括性”的父节点,然后通过父节点对爬取的页面进行解析得到子节点集,之后再利用for循环遍历节点集,从而再利用子节点提取出用户名、用户发表的段子、点赞数、评论数、帖子包含的图片。最后将其存储在字典里写入json文件。
# -*- coding:utf-8 -*-
#
from urllib import request as urllib2
from lxml import etree
import json
headers = {
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:57.0) Gecko/20100101 Firefox/57.0',
}
def spider(headers):
# 只爬取第一页的数据 可以自行修改
url = 'https://www.qiushibaike.com/8hr/page/1/'
request = urllib2.Request(url, headers=headers)
response = urllib2.urlopen(request)
html = response.read()
dom = etree.HTML(html)
# 模糊查询 存储为根节点
node_list = dom.xpath('//div[contains(@id,"qiushi_tag")]')
# 遍历节点列表
for node in node_list:
# 得到用户名
userName = node.xpath('./div/a/h2/text()')
# print(''.join(userName).split())
# 得到图片
image = node.xpath('.//img[@class="illustration"]/@src')
# 得到段子
text = node.xpath('./a/div[@class="content"]/span/text()')
# 得到点赞数
zan_num = node.xpath('.//span[@class="stats-vote"]/i/text()')
# 得到评论数
comments_num = node.xpath('.//a/i/text()')
# 爬取用户名 图片 段子 赞数 评论数
items = {
'userName':userName,
'image':image,
'text':text,
'zan':zan_num,
'comments':comments_num,
}
# 利用open as语句以追加的方式写入文件
with open('qiushi.json','a',encoding='utf-8') as file:
file.write(json.dumps(items, ensure_ascii=False) + '\n')
if __name__ == '__main__':
spider(headers)