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

 结果如下:

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值