爬取網站: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
結果如下: