In the actual crawler development, we often need to take the data crawled to do further processing. For example, the data to be crawled to save, save to the database, or save with the file, at this time further operation we can write the pipelines.py file to achieve. Next I'll write a crawl of my Python blog data and save it to a file: pipelines
Import codecs
import JSON
class Csdnpipeline (object):
def __init__ (self):
self.file = Codecs.open (" Csdn.json "," WB ", encoding=" Utf-8 ")
def process_item (self, item, spider):
array = []
print (len (item[" name "]))) for the
Index in range (len (item[" name ")):
name = item[" Name "][index]
date = item[" Date "][index]
Reply = item["Reply"][index]
desc = item["desc"][index]
datadict = {"Name": Name, "desc":d ESC, "date":d ate, " Reply ": reply}
array.append (datadict)
info = json.dumps (array, ensure_ascii=false)
# Write all data to file
Self.file.write (Info)
return item
def close_spider (self,spider):
self.file.close ()
Item
Import Scrapy
class Csdnitem (scrapy. Item): # define the fields for your item here is like
:
name = Scrapy. Field ()
desc = scrapy. Field ()
date = Scrapy. Field ()
reply = Scrapy. Field ()
Spider
Import scrapy from
csdn.items import Csdnitem
class Csdnspider (scrapy. Spider):
name = ' csdn '
allowed_domains = [' csdn.net ']
start_urls = [' http://blog.csdn.net/y472360651/ article/category/6920392 ']
def parse (self, Response):
item = Csdnitem ()
item["name"] = Response.xpath ("/ /span[@class = ' link_title ']/a/text () "). Extract ()
item[" desc "] = Response.xpath ("//div[@class = ' Article_ Description ']/text () "). Extract ()
item[" date "] = Response.xpath ("//span[@class = ' link_postdate ']/text () "). Extract ()
item["reply"] = Response.xpath ("//span[@class = ' Link_view ']/text ()"). Extract ()
# must use yield, Otherwise, process_item in pipelines will not execute
yield item
Settings Settings
After writing the above code, you need to configure the settings
Item_pipelines = {
' CSDN.pipelines.CSDNPipeline ': +,
}
In fact, this code already exists in Settings, but is annotated, just open the comment