NT3*_*3RP 6 python django scrapy
我一直在使用Scrapy,但遇到了一些问题.
DjangoItem有一个save方法来使用Django ORM持久化项目.这很好,除非我多次运行一个scraper,即使我可能只想更新以前的值,也会在数据库中创建新项目.
查看文档和源代码后,我没有看到任何更新现有项目的方法.
我知道我可以调用ORM来查看项目是否存在并更新它,但这意味着要为每个对象调用数据库,然后再次保存项目.
如果项目已存在,我该如何更新?
NT3*_*3RP 10
不幸的是,我发现完成此任务的最佳方法是完全按照所述内容进行操作:检查数据库中是否存在该项目,如果存在django_model.objects.get则更新它.
在我的设置文件中,我添加了新管道:
ITEM_PIPELINES = {
# ...
# Last pipeline, because further changes won't be saved.
'apps.scrapy.pipelines.ItemPersistencePipeline': 999
}
Run Code Online (Sandbox Code Playgroud)
我创建了一些辅助方法来处理创建项模型的工作,并在必要时创建一个新方法:
def item_to_model(item):
model_class = getattr(item, 'django_model')
if not model_class:
raise TypeError("Item is not a `DjangoItem` or is misconfigured")
return item.instance
def get_or_create(model):
model_class = type(model)
created = False
# Normally, we would use `get_or_create`. However, `get_or_create` would
# match all properties of an object (i.e. create a new object
# anytime it changed) rather than update an existing object.
#
# Instead, we do the two steps separately
try:
# We have no unique identifier at the moment; use the name for now.
obj = model_class.objects.get(name=model.name)
except model_class.DoesNotExist:
created = True
obj = model # DjangoItem created a model for us.
return (obj, created)
def update_model(destination, source, commit=True):
pk = destination.pk
source_dict = model_to_dict(source)
for (key, value) in source_dict.items():
setattr(destination, key, value)
setattr(destination, 'pk', pk)
if commit:
destination.save()
return destination
Run Code Online (Sandbox Code Playgroud)
然后,最后的管道非常简单:
class ItemPersistencePipeline(object):
def process_item(self, item, spider):
try:
item_model = item_to_model(item)
except TypeError:
return item
model, created = get_or_create(item_model)
update_model(model, item_model)
return item
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2047 次 |
| 最近记录: |