2017-01-10 2 views
0

나는 꽤 오래 동안 Scrapy와 Mongodb에 어려움을 겪어 왔습니다. http://antispam.imp.ch/spamlist에서 성공적으로 데이터를 크롤링했지만 파이프 라인이 끝나면 KeyError: 'AntispamItem does not support field: _id'이 방금 나타났습니다. 저는 Python과 Mongodb에 익숙하지 않습니다. 오류 로그에서 내 코드를 잘못 해석 할 수없는 것 같습니다. Google에서 모든 솔루션을 이미 시도했습니다. mongodb에 삽입 할 때 id가 자동으로 생성된다고 생각했습니다. 그러나 그것이 사실이 아닌 것 같습니다. 누군가이 문제를 해결하는 방법을 말해 줄 수 있다면 정말 고마워 할 것입니다.Scrap.Pipeline을 사용하여 스크랩 한 항목을 Mongodb에 저장할 때 오류가 발생했습니다.

import pymongo 
from scrapy.conf import settings 
class AntispamPipeline(object): 
    def __init__(self): 
     connection=pymongo.MongoClient('localhost',27017) 
     db=connection['threat_ip'] 
     self.collection=db['data_center_test'] 

    def process_item(self, item, spider): 
     self.collection.insert(item) 
     return item 

, 나는 "If the document does not specify an _id field, then MongoDB will add the _id field and assign a unique ObjectId for the document before inserting." 그래서 사람이 무슨 일이 있었는지 말해 수 않습니다 MongoDB를 공식 문서에서 거미와 오류 로그

import re 
import scrapy 
from antispam.items import AntispamItem 
class Antispam_Spider(scrapy.Spider): 
    name='antispam' 
    start_urls=['http://antispam.imp.ch/spamlist'] 
    def parse(self, response): 
     content=response.body 
     ip_name=re.findall('\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}',content) 
     content_list=content.split('\t') 
     content_data=[] 
     for i in range(0,len(content_list)-1): 
      if content_list[i] in ip_name: 
       dic={} 
       dic['name']=content_list[i] 
       dic['time']=content_list[i+2] 
       content_data.append(dic) 
      else: 
       pass 

     for dic in content_data: 
      item=AntispamItem() 
      item['name']=dic['name'] 
      item['time']=dic['time'] 
      item['type']='Spam Sources' 
      yield item 




KeyError: 'AntispamItem does not support field: _id' 
2017-01-10 15:59:02 [scrapy.core.scraper] ERROR: Error processing {'name': '223.230.65.17', 
'time': 'Mon Jan 9 01:07:38 2017', 
'type': 'Spam Sources'} 
Traceback (most recent call last): 
    File "c:\python27\lib\site-packages\twisted\internet\defer.py", line 651, in _runCallbacks 
    current.result = callback(current.result, *args, **kw) 
    File "V:\work\antispam\antispam\pipelines.py", line 16, in process_item 
    self.collection.insert(item) 
    File "c:\python27\lib\site-packages\pymongo\collection.py", line 2469, in insert 
    check_keys, manipulate, write_concern) 
    File "c:\python27\lib\site-packages\pymongo\collection.py", line 562, in _insert 
    check_keys, manipulate, write_concern, op_id, bypass_doc_val) 
    File "c:\python27\lib\site-packages\pymongo\collection.py", line 524, in _insert_one 
    doc['_id'] = ObjectId() 
    File "c:\python27\lib\site-packages\scrapy\item.py", line 63, in __setitem__ 
    (self.__class__.__name__, key)) 
KeyError: 'AntispamItem does not support field: _id' 

보고 다음과 같은 : 다음 는 Pipelines.py입니까?

+0

antispam.items.AntispamItem 모델의 모양은 무엇입니까? – Tanzaho

+0

@Tanzaho 수입 scrapy '클래스 AntispamItem (scrapy.Item) : # 여기에 귀하의 항목에 대한 필드를 정의 같은 : # 이름 = scrapy.Field() 이름 = scrapy.Field() 유형 = scrapy.Field () 시간 = scrapy.Field()' –

+0

문제가 해결되었습니다! http://stackoverflow.com/questions/26952080/saving-scrapy-items-to-mongodb –

답변

0

댓글을 게시 한 후 짧게 발견되었습니다. 적어도 제 경우에는 Itemdefined by scrapy으로 삽입하려고했기 때문입니다. 문서에서 setting an unknown field value will produce this error을 볼 수 있습니다. MongoDB가 _id 필드를 설정/추가하려고합니다.

그래서이 변화 :

.insert_one(my_item) 

이에 :

.insert_one(dict(my_item)) 

나를 위해 그것을 해결.