前面已经讲了scrapy框架的创建和运行,包括一些中间件的的设置和使用。 现在开始讲如何通过管道pipelines进行数据的存储,主要讲存储成文件形式。
我们知道创建的scrapy项目有一个pipelines.py的文件,这个文件就是用来存储我们定义的管道处理类的地方。不过要使用pipelines,首先需要在settings.py文件里面配置pipelines。
在setting.py文件里面找到关于pipelines的设置部分,默认设置如下所示。
# Configure item pipelines
# See https://doc.scrapy.org/en/latest/topics/item-pipeline.html
#ITEM_PIPELINES = {
# 'hello.pipelines.HelloPipeline': 300,
#}
在上面的代码中,‘hello.pipelines.HelloPipeline’
中的hello为项目名(即scrapy项目核心目录名),pipelines代表hello目录下的pipelines.py文件的文件名,HelloPipeline代表对应的pipelines文件里的类。所以‘hello.pipelines.HelloPipeline’
相当于告诉系统pipelines文件在哪里。同时又说明了pipelines文件里面对应的类是什么。该项设置的格式为
“核心目录名称.pipelines文件名.对应类名”
这里我们先讲如何存储到文件里面。所以在pipelines.py文件里面定义一个FilePineline类。 默认配置修改为
ITEM_PIPELINES = {
'hello.pipelines.FilePineline': 300,
}
打开项目里面的pipelines.py文件,里面的类修改为FilePineline,并将代码修改如下。
class FilePineline(object):
# init()为类的初始化方法,开始的时候调用
def init(self):
# 首先用写入的方式创建或者打开一个普通文件用于存储爬取到的数据
self.file = open("/Users/zhouruiyong/Desktop/python/hello/hello/hello.txt","w")
#processitem()为pipelines中的主要处理方法,默认会自动调用
def processitem(self, item, spider):
#设置每行要写的内容
l = str(item["title"]) +"\n"
#此处输出,方便程序的调试
print(l)
#将对应信息写入文件中
self.file.write(l)
return item
def close_spider(self,spider):
#关闭文件
print("文件关闭")
self.file.close()
关于item.py和spider的定义,这边全部用之前章节的例子,最好可以看一下之前关于scrapy框架的文章。
通过cd进入项目目录,输入命令运行爬虫
scrapy crawl baiduSpider —nolog
baiduSpider 是之前的例子中创建的爬虫名称。 命令行运行结果
$ scrapy crawl baiduSpider —nolog
[<Selector xpath=’/html/head/title/text()’ data=’百度一下,你就知道’>]
[<Selector xpath=’/html/head/title/text()’ data=’新浪首页’>]
[<Selector xpath=’/html/head/title/text()’ data=’腾讯首页’>]
文件关闭
对应路径的hello.txt文件也有写入的内容。 这里要特别说明,在爬虫文件BaiduspiderSpider中的parse()方法末尾一定要加入yield item 代码如下
def parse(self, response):
item = HelloItem()
item["title"] = response.xpath("/html/head/title/text()")
print(item["title"])
yield item
不然通道中的process_item()方法将执行不到。 还有就是l = str(item[“title”]),这里务必加一个str方法进行字符串转化,否则输出内容可能为空。 如果是要保存json格式的文件,我们可以再pipelines文件里面重新弄一个类,如下
import json
class JsonFilePineline(object):
#__init()为类的初始化方法,开始的时候调用
def __init(self):
#首先用写入的方式创建或者打开一个普通文件用于存储爬取到的数据
self.file = open(“/Users/zhouruiyong/Desktop/hello.json”,“w”)
#process_item()为pipelines中的主要处理方法,默认会自动调用
def process_item(self, item, spider):
#先用dict将item转换成一个字典,再用json的dumps方法处理自定数据
h = json.dumps(dict(item))+“\n”
#此处输出,方便程序的调试
print(h)
#将对应信息写入文件中
self.file.write(h)
return item
def close_spider(self,spider):
#关闭文件
print(“json文件关闭”)
self.file.close()
需要在settings.py注册该类
ITEM_PIPELINES = {
‘hello.pipelines.JsonFilePineline’: 400,
}
运行结果如下:
{“title”: “[<Selector xpath=‘/html/head/title/text()’ data=‘\u767e\u5ea6\u4e00\u4e0b\uff0c\u4f60\u5c31\u77e5\u9053’>]”}
{“title”: “[<Selector xpath=‘/html/head/title/text()’ data=‘\u65b0\u6d6a\u9996\u9875’>]”}
{“title”: “[<Selector xpath=‘/html/head/title/text()’ data=‘\u817e\u8baf\u9996\u9875’>]”}
json文件关闭
可以看到乱码,这里需要做一点修改,dumps的时候改成如下
h = json.dumps(dict(item),ensure_ascii= False)
这样就可以正常显示中文了
[<Selector xpath=’/html/head/title/text()’ data=’百度一下,你就知道’>]
[<Selector xpath=’/html/head/title/text()’ data=’新浪首页’>]
[<Selector xpath=’/html/head/title/text()’ data=’腾讯首页’>]
json文件关闭
另外有一点要注意,在前面的爬虫文件parse方法里面,item对应字段的赋值,需要用str方法保证值为字符串,否则dumps的时候会出错。 如下:
def parse(self, response):
item = HelloItem()
item[“title”] = str(response.xpath(“/html/head/title/text()”))
yield item
注意: 代理ip可能会用不了,请选择能用的代理ip。
欢迎关注本人公众号和小程序,谢谢


网友评论