Adding fields to item in scrapy from list
Adding fields to item in scrapy from list
I have a long list of fields to add to a scrapy item but can't figure out how to do it. Basically I am trying to get the output of
class myItem(scrapy.Item):
a = scrapy.field()
b = scrapy.field()
But I want to create it from a list like
['a','b']
I tried
fields = ['a','b']
def generateFields(fields):
item = myItem()
for field in fields:
field = scrapy.Field()
return item
But that didn't work. Thanks!
1 Answer
1
You can manage it by using python magic method __dict__ pretty much as:
__dict__
fields = ['a', 'b', 'c']
class MyItem(scrapy.Item):
def __init__(self):
for f in fields:
self.__dict__[f] = scrapy.field()
my_item = MyItem()
And so on...
Seems that my previous comment is valid for usual python classes, not for scrapy.Item class. Following code is working:
scrapy.Item
from scrapy import Item, Field
fields = ['a', 'b', 'c']
def generate_item(fields):
item = Item()
for f in fields:
item.fields[f] = Field()
return item
item_instance = generate_item(fields)
item_instance['a'] = 'some_value'
item_instance['b'] = 12
print(item_instance)
__init__
I hate this editor (: item.__dict__[field] = scrapy.Field()
– Michael Savchenko
Jul 1 at 13:00
I've updated the answer with your function...
– Michael Savchenko
Jul 1 at 13:04
Thanks, but I just tried running your code (first box) and when I try to return the item I get File "C:UsersJoeAnaconda2libsite-packagesscrapyitem.py", line 74, in getattr raise AttributeError(name) AttributeError: _values
– AlexTheBoy
Jul 1 at 14:02
Updated my answer once again (: seems to work now
– Michael Savchenko
Jul 1 at 17:47
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
I was wondering if it can be done without
__init__?– Tarun Lalwani
Jul 1 at 12:56