1. 程式人生 > >【實戰】scrapy 爬取果殼問答!

【實戰】scrapy 爬取果殼問答!

引言

學爬蟲的同學都知道,Scrapy是一個非常好用的框架,可以大大的簡化我們編寫程式碼的工作量。今天我們就從使用Scrapy爬取果殼問答。

需求分析

爬取果殼問答中精彩回答的標題和答案。

知識點

爬取資料:Scrapy

資料庫:Mongo

建立專案和爬蟲

建立專案:

scrapy的建立專案命令為startproject,這裡我們使用這個命令建立一個果殼的專案。

建立完專案之後,進入專案資料夾建立爬蟲。建立爬蟲的命令為genspider。這裡我們使用crawl模板來建立spider。

部分程式碼

建立完成專案和爬蟲後,我們使用IDE開啟專案。首先修改settings檔案。將ROBOTSTXT_OBEY設定成False,將User-Agent的註釋開啟並根據自身使用的瀏覽器進行設定。將DOWNLOAD_DELAY設定為1.(這裡是下載延時,為了防止被封IP,這裡設定延時1秒,可以根據實際情況調整)

Items檔案:在Items檔案中,我們建立三個屬性,分別是question、answer和_id。其中_id是用來存入mongoDB中使用。

class GuokrItem(scrapy.Item):
    # define the fields for your item here like:
    # name = scrapy.Field()
    question = scrapy.Field()
    answer = scrapy.Field()
    _id = scrapy.Field()

Spider檔案:在Spider檔案中,我們需要補齊兩個rule,第一個規則是從列表中篩選出其他列表頁面的url,第二個規則是從列表中篩選出問題的詳細地址。

在parse_item中實現資訊的提取,這裡我們使用css選擇器來提取想要的內容,提取完成之後,將item返回。

# -*- coding: utf-8 -*-
import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule
from Guokr.items import GuokrItem

class GuokrSpider(CrawlSpider):
    name = 'guokr'
    allowed_domains = ['guokr.com']
    start_urls = ['https://www.guokr.com/ask/highlight/?page=1']

    rules = (
        Rule(LinkExtractor(allow=r'page='), follow=True),
        Rule(LinkExtractor(allow=r'question'), callback='parse_item', follow=False),
    )

    def parse_item(self, response):
        item = GuokrItem()
        item['answer'] = response.css(".answer-txt p::text").extract()
        item['question'] = response.css("#articleTitle::text").extract_first()
        yield item

Pipelines檔案:在pipelines檔案中我們需要實現內容的儲存,這裡提供了兩個方式,一種是寫到本地txt檔案,一種是寫到mongoDB中。

# -*- coding: utf-8 -*-

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html
from scrapy.exporters import JsonItemExporter
import pymongo

class GuokrPipeline(object):
    def open_spider(self,spider):
        self.file = open('guokr.txt','wb')
        self.exporter = JsonItemExporter(self.file)
        self.exporter.start_exporting()

        self.con = pymongo.MongoClient()
        self.database = self.con['guokr']
        self.conllection = self.database['guokr']

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

        self.conllection.insert_one(item)

    def close_spider(self,spider):
        self.exporter.finish_exporting()
        self.file.close()

        self.con.close()

最後我們需要在settings檔案中開啟pipelines。(此步略)

部分結果:

至此,我們使用了很少的程式碼就完成了對果殼問答的爬取。

原始碼

連結:連結:https://pan.baidu.com/s/1MRnkfKIAvsxECMRqygdfCA 提取碼 提取碼:ls65