python - 如何在scrapy中使用Itempipeline将项目保存到数据库中

标签 python django

我的蜘蛛的parse_items中有这段代码

 def parse_items(self, response):

        hxs = HtmlXPathSelector(response)
        sites = hxs.select("//li[@class='mod-result-entry  ']")
        items = []


        for site in sites[:2]:
            item = MyItem()
            item['title'] = myfilter(site.select('dl/a').select("string()").extract())
            item['company'] = myfilter(site.select('dl/h2/em').select("string()").extract())
            items.append(item)
        return items

现在我想使用 Django 模型将项目保存在数据库中。一种工作正常的方法,我只是像这样使用

item = MYapp.MyDjangoItem()
item.title = myfilter(site.select('dl/a').select("string()").extract())
item.save()

现在一切正常

现在我想知道这种方法是否适合保存在数据库中。

我的意思是为什么我们需要 scrapy 中描述的 itempipeline 东西。这样做有什么好处吗?

Fir e,g这是我的管道

class MyPipeline(object):

    def __init__(self):
        self.ids_seen = set()

    def process_item(self, item, spider):
       Myitem = Myapp.DjamgoItem()
       Myitem.title = item['title']
       MyItem.save()

可以吗

我的代码将如何调用这个管道。我对此感到困惑

最佳答案

管道对于清理公共(public)值非常有用。如果您只有一种类型的对象,这尤其有用。通过管道保存 django 模型实例很好,scrapy 文档中的示例通过向管道添加 JsonWriter 来执行相同的操作。 (这在现实生活中是不必要的,因为有内置的功能)

大声思考:

但是,当您创建多个对象时,您可能希望区分处理。因为蜘蛛作为参数传递给 process_item 函数,所以这很容易,但是(imo),这往往会变得相当冗长:

class MyPipeline(object):
    def process_item(self, item, spider):
       if spider == 'A':
           if item.somefield:
               #... etc
       elif spider == 'B':
           #... etc

我个人喜欢 Django 中表单清理背后的想法(通过前面带有“clean_”的字段名称检查现有函数)。为了在 scrapy 中实现类似的功能,我扩展了 Item 类:

class ExtendedItem(Item):
    def _process(self):
        [getattr(self, func)() for func in dir(self) if func.split('_')[-1] in self.fields and callable(getattr(self, func))]

所以现在你可以这样做:

class Book(ExtendedItem):
    title = Field()

    def _process_title(self):
        title = self['title'].lower()
        self.update(title=title)

在这种情况下,您可以使用管道调用 item._process()。

免责声明

我在 github.com 上提出了这个想法不久以前。可能有更好的实现(代码方面)。

关于python - 如何在scrapy中使用Itempipeline将项目保存到数据库中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13814329/

相关文章:

python - 如何在python中将包含数字和字符的向量转换为数值向量?

django - 具有多个值的 Tastypie 过滤

python - 如何处理/映射自定义 postgresql 类型到 Django 模型

python - Django 项目寻找 "attribute ' _session_cache'”

Python 'for word in word' 循环

python - unicode,而不是 python 中的 str

python - Django 1.11 : What fails `pickle` in my parallel test run?

python - 如何从jupyter笔记本导出清理后的数据,而不是原始数据

python - Django-Ldap-身份验证

django - 在 Django 中,如何在提交 CreateView 时重定向到 UpdateView?