2016-03-21 4 views
-2

私は非常にPythonの新機能ですが、これはとても簡単な問題です(そして、うまくいくはずです)。Pythonその他のif文を無視する

このコードは、アイテムが空でない場合にmysql dbにデータを挿入する必要があります。しかし、何らかの理由で、Pythonは特定のif文を評価するのは、その上のif文もtrueと評価された場合のみです。

def process_item(self, item, spider): 
    now = datetime.datetime.now() 
    self.cursor.execute(""" INSERT INTO `diseases`(`medical_term`, `local_term`, `date_added`, `from_getbetter`) VALUES (%s,%s,%s,%s)""", (item['title'][0].encode('utf-8'), item['desc'][0].encode('utf-8'), now.strftime('%Y-%m-%d %H:%M:%S'), 0))    
    disease_id = self.cursor.lastrowid 
    if item['head']: 
     self.cursor.execute(""" INSERT INTO `disease_locations`(`disease_id`, `location`) VALUES (%s,%s)""", (disease_id, item['head'][0].encode('utf-8'))) 
    if item['neck']: 
     self.cursor.execute(""" INSERT INTO `disease_locations`(`disease_id`, `location`) VALUES (%s,%s)""", (disease_id, item['neck'][0].encode('utf-8'))) 
    if item['nose']: 
     self.cursor.execute(""" INSERT INTO `disease_locations`(`disease_id`, `location`) VALUES (%s,%s)""", (disease_id, item['nose'][0].encode('utf-8'))) 
    if item['mouth']: 
     self.cursor.execute(""" INSERT INTO `disease_locations`(`disease_id`, `location`) VALUES (%s,%s)""", (disease_id, item['mouth'][0].encode('utf-8'))) 

たとえば、['nose']アイテムは、アイテムの頭と首がヌルでない場合にのみ挿入されます。 Database screenshot

こんにちは、私は項目が辞書であると仮定:(

+0

あなたのチェックは 'もしアイテム[「頭」]でなければなりません[0]:'とする代わりに置き換えるだけで、キーと同じコードを繰り返すことのように –

+0

、あなたは内の位置のための 'としてそれを書くことができます。 ['頭'、 '首'、...]:項目内の場所:... – Schwern

+0

@Schwern非常にありがとう!あなたの提案は働く:)それはwよりずっと優れている帽子私がやっていた –

答えて

-1

項目は、キー「頭」をしていない場合ステートメントは、次のように記述しなければならない場合、スクリプトは。あなたのすべてをエラーが発生します助けてください:

if 'head' in item: 
+0

これは質問に記載されている問題とは関係ありません。 –

関連する問題