了解更多关注微信公众号“木下学Python”吧~
目录
数据的存储容器,在对数据进行有处理的操作时,必须要用,例如写入txt,插入数据库等
数据的存储容器,在对数据进行有处理的操作时,必须要用,例如写入txt,插入数据库等
没有对数据进行操作时,可以不使用
ItemLoader
文档:https://doc.scrapy.org/en/latest/topics/loaders.html
https://blog.youkuaiyun.com/zwq912318834/article/details/79530828
Field 元数据
可以对存储到容器的数据进行操作
例如在写入 csv 时,对应的数据时列表,但想写入的是字符串,将元数据字段串行化,serializer 是 scrapy 导出源代码里面规定好的一个键,用该键获取元数据
class BookItem(Item):
...
author = Field(serializer=lambda x: ','.join(x))
..
容器实例化在 spider 中
在 spider 文件中,要导入容器模块,实例化使用时实例化在 parse 函数里面,并且一般是在 for 循环里面,如果在 for 循环外面,那最后容器可能到最后因为都是把上一次的数据覆盖,最后就只剩一条数据,所以要在循环里面实例化,每一次都返回一个新的字段
对:
class BooksSpider(scrapy.Spider):
name = 'books'
allowed_domains = ['books.toscrape.com']
start_urls = ['http://books.toscrape.com/']
def parse(self, response):
"""
提取数据
用 css 提取每一本书的标签
:param response:
:return:
"""
for sel in response.css('article.product_pod'):
book = BooksSpiderItem() !!!!!!!!!!!!!!!!!!!!!!!!这里
book['name'] = sel.xpath('./h3/a/@title').extract_first()
book['price'] = sel.css('p.price_color::text').extract_first()
yield book
#提取下一页链接
next_url = response.css('ul.pager li.next a::attr(href)').extract_first()
if next_url:
next_url = response.urljoin(next_url)
yield scrapy.Request(next_url,callback=self.parse)
错:
class BooksSpider(scrapy.Spider):
name = 'books'
allowed_domains = ['books.toscrape.com']
start_urls = ['http://books.toscrape.com/']
book = BooksSpiderItem() !!!!!!!!!!!!!!!!!!!这里
def parse(self, response):
"""
提取数据
用 css 提取每一本书的标签
:param response:
:return:
"""
for sel in response.css('article.product_pod'):
book['name'] = sel.xpath('./h3/a/@title').extract_first()
book['price'] = sel.css('p.price_color::text').extract_first()
yield book
#提取下一页链接
next_url = response.css('ul.pager li.next a::attr(href)').extract_first()
if next_url:
next_url = response.urljoin(next_url)
yield scrapy.Request(next_url,callback=self.parse)
FilePipeline 文件下载管道的容器
file_urls 为保存下载链接的容器字段,为列表
files 为下载信息的容器的列表,这个在导出文件时必须要,而且不要拼错,拼错保存不了结果
下载完 item['file_urls'] 中的所有文件后,会将各文件的下载结果信息收集另一个你一个列表,赋给 item 的 fiels 字段(item['files'])下载结果包括:
- path 文件下载到本地的路径(相对于 FILES_STORE 的相对路径)
- checksum 文件的校验和,一般默认用于作为文件名,是经过散列值计算的
- url 文件的 url 地址
class MatplotlibExamplesItem(scrapy.Item):
#文件 url
file_urls = scrapy.Field()
#保存下载的文件
files = scrapy.Field()