far*_*awa 14 python scrapy scrapy-spider scrapy-pipeline
我是新手scrapy
,我的任务很简单:
对于给定的电子商务网站:
抓取所有网站页面
寻找产品页面
如果URL指向产品页面
创建一个项目
处理项目以将其存储在数据库中
我创建了蜘蛛,但产品只是打印在一个简单的文件中.
我的问题是项目结构:如何在蜘蛛中使用物品以及如何将物品发送到管道?
我找不到使用项目和管道的项目的简单示例.
Adr*_*uer 39
那么,项目的主要目的是存储您抓取的数据.scrapy.Items
基本上都是字典.要声明您的项目,您必须创建一个类并添加scrapy.Field
它:
import scrapy
class Product(scrapy.Item):
url = scrapy.Field()
title = scrapy.Field()
Run Code Online (Sandbox Code Playgroud)
您现在可以通过导入产品在蜘蛛中使用它.
对于高级信息,我让你在这里查看文档
首先,你需要告诉你的蜘蛛使用你的custom pipeline
.
在settings.py文件中:
ITEM_PIPELINES = {
'myproject.pipelines.CustomPipeline': 300,
}
Run Code Online (Sandbox Code Playgroud)
您现在可以编写管道并使用您的项目.
在pipeline.py文件中:
from scrapy.exceptions import DropItem
class CustomPipeline(object):
def __init__(self):
# Create your database connection
def process_item(self, item, spider):
# Here you can index your item
return item
Run Code Online (Sandbox Code Playgroud)
最后,在你的蜘蛛中,yield
一旦它被填满你需要你的物品.
spider.py示例:
import scrapy
from myspider.items import Product
class MySpider(scrapy.Spider):
name = "test"
start_urls = [
'http://www.exemple.com',
]
def parse(self, response):
doc = Product()
doc['url'] = response.url
doc['title'] = response.xpath('//div/p/text()')
yield doc # Will go to your pipeline
Run Code Online (Sandbox Code Playgroud)
希望这会有所帮助,这里是管道的文档:项目管道