Scrapy :全站爬取文學文章

爬取網站:www.rensheng5.com

爬取內容:整站文章

爬取字段:名稱  時間 作者  內容

保存:以每個文章的名稱命名保存爲txt

本次採用通用爬蟲爬網站:

環境:Ubuntu  python3.7

在終端創建項目模板 CrawlSpider

重要的就是Rule正則表達式的構造

項目創建可見我的其他scrapy爬蟲,在此不再贅述

直接上主要代碼:

 rules = (
        Rule(LinkExtractor(allow=r'\w+/id-\d+.html'), callback='parse_item', follow=True),

    )

 

 解析代碼:


        item['name'] = response.xpath('//div[@class="artview"]/h1/text()').extract_first()
        date = response.xpath('//div[@class="artinfo"]//text()').extract()
        item['date'] = ' '.join(date).split('點擊')[0].replace('\u3000', ' ').strip()
        content = response.xpath('//div[@class="artbody"]//p/text()').extract()
        item['content'] = ' '.join(content).replace('\u3000', '').replace('\r\n', ' ').strip()

settings設置:

將 ITEM_PIPELINES的註釋去掉

item設置:

設置三個字段;name  date content

piplines設置:

這個主要是用於保存數據的代碼如下:

    def process_item(self, item, spider):
        filename = item['name']
        f = open(filename+'.txt', 'w', encoding='utf8')
        f.write(item['name']+'\n')
        f.write(item['date']+'\n')
        f.write(item['content'])
        f.close()
        return item

 結果如下:

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章