2015-02-24 33 views
0

我試圖使用python將一個feed導入到pythoneverywhere上的Mysql數據庫,但我似乎無法讓它工作。這裏是我使用的代碼。使用python import rss feed into MySQL數據庫

import MySQLdb 
import feedparser 

myfeed = feedparser.parse("http://www.couponchief.com/rss/") 

for item in myfeed['items']: 
     title = item.title 
     link = item.link 
     description = item.description 
     print title 
     print link 
     print description 

     db =             
     MySQLdb.connect('mysql.server','lesmun','*******','lesmun$default'); 

     with db: 

      cur = db.cursor() 
      cur.execute("INSERT INTO ini(title, link, description)VALUES(%s,   
      %s, %s)", (title,link,description)) 
      print 'Succesfull!' 


# close the cursor 
      cur.close() 

# close the connection 
     db.close() 

有什麼建議嗎?

+1

實際的問題是什麼?是否有追溯,錯誤信息或其他有關錯誤的描述? – mhawke 2015-02-24 00:56:26

+0

我不知道,它只是沒有做任何事情,當我運行的代碼似乎好,但它沒有注入任何東西,並且它不打印我的項目@mha​​wke – 2015-02-24 01:18:50

+0

你有沒有想過使用服務,如[Superfeedr](https:// superfeedr.com),它只會使用webhook向您發送JSON中的RSS內容?這將爲您節省解析和輪詢部分:) – 2015-02-24 03:26:47

回答

0

可能您正在使用舊版本的MySQLdb,它不支持自動提交事務的上下文管理器。

您可以升級到最新版本make your own,或者您可以在關閉連接前明確呼叫db.commit()

另外,爲插入的每一行創建新的連接到數據庫並創建新的遊標並不是必需的(或可取的)。你的代碼會寫得更好:

import MySQLdb 
import feedparser 

myfeed = feedparser.parse("http://www.couponchief.com/rss/") 

# get connection and cursor upfront, before entering loop 
with MySQLdb.connect('mysql.server','lesmun','*******','lesmun$default') as db: 
    cur = db.cursor() 

    for item in myfeed['items']: 
     title = item.title 
     link = item.link 
     description = item.description 
     print title 
     print link 
     print description 

     cur.execute("INSERT INTO ini (title, link, description) VALUES (%s, %s, %s)", (title, link, description)) 
     print 'Succesfull!' 

# db.commit() # for older MySQLdb drivers