涉及到详情页爬取
目录结构:
kaoshi_bqg.py
import scrapyfrom scrapy.spiders import Rulefrom scrapy.linkextractors import LinkExtractorfrom ..items import BookBQGItemclass KaoshiBqgSpider(scrapy.Spider): name = 'kaoshi_bqg' allowed_domains = ['biquge5200.cc'] start_urls = ['https:// # print(os.path.dirname(os.path.dirname(__file__))) D:/Users/Administrator/PycharmProjects/wh1901 if not os.path.exists(xs_path): # 如果目录不存在 os.mkdir(xs_path) if not os.path.exists(fiction_path): os.mkdir(fiction_path) # 创建目录 chapter = item['chapter'] content = item['content'] file_path = os.path.join(fiction_path, chapter) + '.txt' # 在 该目录下面创建 xx .txt 文件 with open(file_path, 'w', encoding='utf-8') as fp: fp.write(content + '\n') print('保存成功')# class XmlyPipeline(object):# def __init__(self):# self.fp = open("xmly.json", 'wb')# # JsonLinesItemExporter 调度器# self.exporter = JsonLinesItemExporter(self.fp, ensure_ascii=False)## def process_item(self, item, spider):# self.exporter.export_item(item)# return item## def close_item(self):# self.fp.close()# print("爬虫结束")starts.py
from scrapy import cmdlinecmdline.execute("scrapy crawl kaoshi_bqg".split())# cmdline.execute("scrapy crawl xmly".split())然后是爬取到的数据
小说
xmly.json
记录一下爬取过程中遇到的一点点问题:
在爬取详情页的的时候, 刚开始不知道怎么获取详情页的 url 以及 上一个页面拿到的字段
- 也就是 yield 返回 请求详情页 里面的参数没有很好地理解
- meta:从其他请求传过来的meta属性,可以用来保持多个请求之间的数据连接。
- url:这个request对象发送请求的url。
- callback:在下载器下载完相应的数据后执行的回调函数。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。