scrapy starproject [爬虫项目名称]
scrapy genspider [爬虫名字] [爬虫作用域] //默认使用basic模板
scrapy genspider -t crawl [爬虫名字] [爬虫作用域] //使用crawl模板创建
Item 是保存爬取到的数据的容器;其使用方法和python字典类似。虽然您也可以在Scrapy中直接使用dict,但是 Item 提供了额外保护机制来避免拼写错误导致的未定义字段错误。
类似在ORM中做的一样,您可以通过创建一个 scrapy.Item
类, 并且定义类型为 scrapy.Field
的类属性来定义一个Item。 (如果不了解ORM, 不用担心,您会发现这个步骤非常简单)
首先根据需要从dmoz.org获取到的数据对item进行建模。 我们需要从dmoz中获取名字,url,以及网站的描述。 对此,在item中定义相应的字段。编辑 tutorial
目录中的 items.py
文件:
import scrapy
class DmozItem(scrapy.Item):
title = scrapy.Field()
link = scrapy.Field()
desc = scrapy.Field()
在pipelines.py
定义三个方法
class TestPipeline(object):
# 初始化操作
def __init__(self):
pass
# 爬虫开启时调用
def open_spider(self,spider):
pass
# 存储相应操作
def process_item(self,item,spider):
return item
# 爬虫关闭时调用
def close_spider(self,spider):
pass
使用 JsonItemExporter 和 JsonLinesItemExporter会让操作变得更简单
import json
from scrapy.exporters import JsonItemExporter
class QsbkPipeline(object):
def __init__(self):
self.file = open(‘FileName.json‘, ‘wb‘)
self.exporter = JsonItemExporter(self.file, ensure_ascii=False, encoding="utf-8")
# 开启数据存储(json)
self.exporter.start_exporting()
# 爬虫开启时调用
def open_spider(self, spider):
print(‘爬虫开启‘)
# 存储相关操作
def process_item(self, item, spider):
self.exporter.export_item(item)
return item
# 爬虫关闭时调用
def close_spider(self, spider):
print("爬虫关闭")
# 关闭数据存储(json)
self.exporter.finish_exporting()
self.file.close()
import json
from scrapy.exporters import JsonLinesItemExporter
class QsbkPipeline(object):
def __init__(self):
self.file = open(‘FileName.json‘, ‘wb‘)
self.exporter = JsonLinesItemExporter(self.file, ensure_ascii=False, encoding="utf-8")
# 爬虫开启时调用
def open_spider(self, spider):
print(‘爬虫开启‘)
# 存储相关操作
def process_item(self, item, spider):
self.exporter.export_item(item)
return item
# 爬虫关闭时调用
def close_spider(self, spider):
print("爬虫关闭")
self.file.close()
import json
class QsbkPipeline(object):
def __init__(self):
self.file = open("FileName.json",‘w‘,encoding = "utf-8")
def open_spider(self,spider):
pass
def process_item(self,item,spider):
Content = json.dumps(item,ensure_ascii=False)
self.file.write(Content+"\n")
return item
def close_spider(self,spider):
self.file.close()
使用命令创建爬虫
scrapy genspider -t crawl [爬虫名字] [域名]
使用LinkExtractors 可以不用程序员自己提取要使用的url,然后发送请求,这些工作都是可以交给LinkExtractors,他会在所有爬的页面中找到满足规则的url,实现自动的爬取,一下对LinkExtractors类做一个简单的介绍;
class scrapy.linkextractors.LinkExtractor(
allow = (),
deny = (),
allow_domains = (),
deny_domains = (),
deny_extensions = (),
restrict_xpath = (),
tags = (‘a‘,‘area‘),
attrs = (‘href‘),
canonicalize = True,
unique = True,
process_value = None
)
定义爬虫的规则类。以下对这个类做一个简单的介绍:
class scrapy.spiders.Rule(
link_extractor,
callback = None,
cb_kwargs = None,
follow = None,
process_links = None,
process_request = None
)
原文:https://www.cnblogs.com/RashoMon/p/13276742.html