【settings模块】
ITEM_PIPELINES ={} (传入的数据要干什么)
IMAGES_URLS_FIELD = '' (去哪里获取url地址)
project_dir = os.path.dirname(os.path.abspath(__file__))
ITEM_PIPELINES ={} (传入的数据要干什么)
IMAGES_URLS_FIELD = '' (去哪里获取url地址)
project_dir = os.path.dirname(os.path.abspath(__file__))
IMAGES_STORE = "" (将文件存储到哪里去)
# 'scrapy.pipelines.images.ImagesPipeline':1, 表示引入scrapy的图片下载方法:路径.ImagesPipeline: 数字越小流入ITEM——PIPELINES管道时越早处理 # IMAGES_URLS_FIELD = 'front_image_url' 告诉下载模块去哪里取url地址(数组形式的url) # os.path.dirname(os.path.abspath(__file__)) 获取到当前文件的目录路径并储存在变量中 # os.path.join(路径,'文件夹名称')
raise ValueError('Missing scheme in request url: %s' % self._url)
ValueError: Missing scheme in request url: h
(是因为要读取的是数组列表形式的值,解决方法把str变成 [ ] )
IMAGES_MIN_HEIGHT = 100
IMAGES_MIN_WIDTH = 100
(设置下载的图片必须大于100*100px)
TypeError: Unicode-objects must be encoded before hashing
(不能处理 Unicode码,需要通过.encoded('utf-8') 转码)
将自定义的函数新建文件夹储存起来(utils)common.py ;比如MD5压缩
【将item数据写入json文件当中】
class JsonWithEncodingPipeline(object):
"""Json文件写入和关闭操作方法函数,需要在settings当中的ITEM_PIPELINES = 进行配置
这个类的操作方式是在 字典中添加[ ] 数组元素
需要导入的类 import codecs和 import json
"""
def __init__(self): # 初始化运行此代码模块函数,既以什么方式打开什么文件
self.file = codecs.open("article.json",'w',encoding='utf-8') # 传入json文件,写入方式打开,文件的编码
def process_item(self,item,spider):
"""如何将item写入json文件当中"""
lines = json.dumps(dict(item),ensure_ascii=False) + "\n" # 将对象编码成 JSON 字典形式的字符串,ensure_ascii=False表示不是以Unicode编码写入,不然容易出错
self.file.write(lines) # 将lines里面的内容写入file的json文件当中
return item
# 写完json文件以后不要将item传递回去,以便下一步进行调用
def spider_closed(self,spider):
"""将json文件关闭的函数方法"""
self.file.close()
class JsonExporterPipleline(object):
"""这里是scrapy提供的json操作方法,与上面的JsonWithEncodingPipeline基本相同
这里输出的形式是以数组 [ ] 来储存,相比上面的自定义json多了 []
需要导入的模块 from scrapy.exporters import JsonItemExporter
"""
def __init__(self):
self.file = open('articleexport.jos','wb') # 以二进制的方式打开
self.exporter = JsonItemExporter(self.file,encoding='utf-8',ensure_ascii=False)
self.exporter.start_exporting()
def close_spider(self,spider):
self.exporter.finish_exporting()
self.file.close()
def process_item(self,item,spider):
self.exporter.export_item(item)
return item