Scrapy 爬取全职高手小说
2019-05-29 22:58
302 查看
Scrapy 爬取全职高手小说
应用 Scrapy框架 ,爬取全职高手小说数据,存于本地json文件。
# items 配置抓取数据字段 import scrapy bookName = scrapy.Field() bookTitle = scrapy.Field() chapterNum = scrapy.Field() chapterName = scrapy.Field() chapterUrl = scrapy.Field() chapterContent = scrapy.Field()
# spider 抓取数据 import scrapy from scrapy.linkextractors import LinkExtractor from scrapy.spiders import CrawlSpider, Rule from novel.items import NovelItem class QuanzhigaoshouSpider(CrawlSpider): name = 'quanzhigaoshou' # allowed_domains = ['qu.la'] start_urls = ['https://www.qu.la/book/32/'] def parse_start_url(self, response): print(response.url) rules = ( Rule(LinkExtractor(allow=r'/book/32/\d+.html'), callback='parse_item', follow=True), ) def parse_item(self, response): print(response.url) item = NovelItem() item['bookName'] = response.xpath('//div[@class="con_top"]/a[2]/text()').get() title = response.xpath('//div[@class="bookname"]/h1/text()').get().split(' ', 1) if len(title) == 1: item['chapterNum'] = '' item['chapterName'] = title[0] elif len(title) == 2: item['chapterNum'] = title[0] item['chapterName'] = title[1] item['chapterUrl'] = response.url item['chapterContent'] = ''.join(response.xpath('//div[contains(@id, "content")]/text()').extract()).strip() yield item
# pipeline 处理数据 import json import codecs import os class NovelPipeline(object): def __init__(self): self.file = codecs.open('quanzhigaoshou.json', 'w', 'utf-8') self.file.write('[') def open_spider(self, spider): print('This spider is starting!') def process_item(self, item, spider): if spider.name == 'quanzhigaoshou': data = json.dumps(dict(item), ensure_ascii=False) + ',\n' self.file.write(data) return item def close_spider(self, spider): print('This spider is end!') self.file.seek(-2, os.SEEK_END) # 定位到倒数第二个字符,即最后一个逗号 self.file.truncate() # 删除最后一个逗号 self.file.write(']') self.file.close()
相关文章推荐
- Python使用Scrapy爬虫框架爬取天涯社区小说“大宗师”全文
- Scrapy+crontab 定时爬取小说更新推送到手机邮件
- scrapy实现爬取全书网小说到本地TXT文件
- Python的scrapy之爬取顶点小说网的所有小说
- 使用django+mysql+scrapy制作的一个小说网站
- 奇文:金庸小说中的第一高手是谁?
- scrapy实现爬取全书网小说到Mysql数据库(附代码)
- Python爬虫实战之使用Scrapy爬起点网的完本小说
- 奇文:金庸小说中的第一高手是谁?
- scrapy笔记(2) - 小试牛刀 (抓取豆瓣推理小说信息)
- 奇文:金庸小说中的第一高手是谁?
- 使用Scrapy爬取顶点小说整个网站的小说,入库Mysql!
- 奇文:金庸小说中的第一高手是谁?
- scrapy抓取小说
- 使用scrapy 抓取顶点小说
- 读书:全职高手
- Python scrapy_splash爬取所有腾讯小说
- 使用scrapy 0.24 制作的小说爬虫
- scrapy初探之实现爬取小说
- scrapy实例 ----- 爬取小说