用 Python 爬取糗事百科

爬取前的准备

糗事百科官网: https://www.qiushibaike.com

段子网址: https://www.qiushibaike.com/text

关于解析html博主选择的方法是使用xpath,如有不懂的同学,可看下面两个表格。如果想要深入学习xpath的相关知识可点击博主给的官方文档的链接进行学习,博主在此声明是为了让读者们能够理解解析式的具体含义。

官网网址: https://lxml.de/tutorial.html

路径表达式

用 Python 爬取糗事百科

匹配属性

用 Python 爬取糗事百科

1.1 查看网页

用 Python 爬取糗事百科

根据上图标记部分可以看到我们主要的要点如下。

  1. 整体部分

  2. 作者名称

  3. 文本内容

  4. 标签翻页

1.2 标签分析

首先我们需要知道我们爬取的所有内容所在标签

用 Python 爬取糗事百科

通过查看开发者选项,发现 <div class ="coll old-style-coll"> 这个标签对应的正是所有内容的整体存放位置,那么我们也可知道之后的所有内容都是从此标签的子标签内提取得到。

分析一番后,我们可以得到获取所有文本内容的解析式如下:

//div[@class = 'col1 old-style-col1']/div

作者名称所在位置

用 Python 爬取糗事百科

由上图我们可以看到作者的位置在 <h2></h2> 这个标签中。

分析一番后,我们可以得到获取作者的解析式如下:

.//h2//text()

作者名称所在位置

用 Python 爬取糗事百科由上图我们可以看到段子的位置在 <div class ="content"></div> 这个标签中。

分析一番后,我们可以得到获取段子的解析式如下:

.//div[@class='content']//text()

标签翻页

用 Python 爬取糗事百科由上图我们可以看到页面的位置在 <ul class ="pagination"></ul> 这个标签中。

分析一番后,我们可以得到获取页面的解析式如下:

//ul[@class='pagination']/li[last()]/a/@href

项目的具体实现

2.1 新建爬虫项目qsbk

用 Python 爬取糗事百科

2.2 settings设置

在创建完成一个scrapy项目后,需要对settings进行一些修改

此处默认为True,需要修改为False。否则无法爬取内容。

用 Python 爬取糗事百科

取消此部分的注解并添加请求头,伪装自己的身份。

2.3 分别提取出作者和文本内容

查看其类型

 duanzidivs = response.xpath("//div[@class = 'col1 old-style-col1']/div")
        print("=")
        print(type(duanzidivs))
        print("=")

用 Python 爬取糗事百科

通过运行我们可以发现其为 SelectorList 类型

通过循环遍历分别打印出作者和文本内容

        for duanzidiv in duanzidivs:
            # strip() 去除前后的空白字符
            author = duanzidiv.xpath(".//h2//text()").get().strip()
            content = duanzidiv.xpath(".//div[@class='content']//text()").getall()
            content = "".join(content).strip()
            print(author)
            print(content)

用 Python 爬取糗事百科

2.4 通过pipeline保存数据

前提准备:放开 ITEM_PIPELINES 的限制

用 Python 爬取糗事百科

第一种方式

class QsbkPipeline:
        def __init__(self):
            self.fp = open("duanzi.json","w",encoding="utf-8")


        def open_spider(self,spider):
            print('爬虫开始了 ...')


        def process_item(self, item, spider):
            item_json = json.dumps(dict(item),ensure_ascii=False)
            self.fp.write(item_json+'\n')
            return item
加python学习qq群:10667510 送python零基础入门学习资料+99个源码
        def close_spider(self,spider):
            self.fp.close()
            print('爬虫结束了 ...')

运行结果:

用 Python 爬取糗事百科

第二种方式:数据量少时使用 JsonItemExporter

from scrapy.exporters import JsonItemExporter
class QsbkPipeline:
    def __init__(self):
        self.fp = open("duanzi.json","wb")
        self.exporter = JsonItemExporter(self.fp,ensure_ascii=False,encoding='utf-8')
        self.exporter.start_exporting()

    def open_spider(self,spider):
        print('爬虫开始了 ...')


    def process_item(self, item, spider):
        self.exporter.export_item(item)
        return item

    def close_spider(self,spider):
        self.exporter.finish_exporting()
        self.fp.close()
        print('爬虫结束了 ...')

运行结果:

第三种方式:数据量多使用 JsonLinesItemExporter

from scrapy.exporters import JsonLinesItemExporter
class QsbkPipeline:
    def __init__(self):
            self.fp = open("duanzi.json","wb")
            self.exporter = JsonLinesItemExporter(self.fp,ensure_ascii=False,encoding='utf-8')
            self.exporter.start_exporting()


    def open_spider(self,spider):
        print('爬虫开始了 ...')

    def process_item(self, item, spider):
        self.exporter.export_item(item)
        return item

    def close_spider(self,spider):
        self.fp.close()
        print('爬虫结束了 ...')

加python学习qq群:10667510 送python零基础入门学习资料+99个源码

运行结果:

用 Python 爬取糗事百科

2.5 定义Item

在 scrapy 中不是说不能直接定义返回字典,但是一般建议现在 item 中定义好然后进行调用

在 item 中分别定义 author 和 content

class QsbkItem(scrapy.Item):
    author = scrapy.Field()
    content = scrapy.Field()

在 qsbk_spider 中也需要进行如下修改

用 Python 爬取糗事百科

2.6 爬取多个页面的实现

前提准备:放开 DOWNLOAD_DELAY 的限制并修改为1

# See also autothrottle settings and docs
DOWNLOAD_DELAY = 1

代码实现

# 定义一个基本的域名
base_domain = "https://www.qiushibaike.com"


next_url = response.xpath("//ul[@class='pagination']/li[last()]/a/@href").get()
# 进行一个简单的判断
if not next_url:
   return
else:
  yield scrapy.Request(self.base_domain+next_url,callback=self.parse)

加python学习qq群:10667510 送python零基础入门学习资料+99个源码

运行并查看结果:

用 Python 爬取糗事百科