爬取网站: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
结果如下: