Feedparser:如果不存在,则插入pg

时间:2015-04-30 10:05:28

标签: python postgresql feedparser

我在这个问题上遇到了几个问题。 所以我试图使用feedparser和psycopg。问题是,我不想要重复数据。

    def dbFeed():
conn_string ="host='localhost' dbname='rss_feed' user='postgres' password='somepassword'"
print ("Connecting to dababase\n ->%s" %(conn_string))

try:
    conn = psycopg2.connect(conn_string)
    cursor = conn.cursor()
    print ("Connected!\n")
except:
    print ('Unable to connect to the database')


 feeds_to_parse=open("C:\\Users\\Work\\Desktop\\feedparser_entry_tests_world.txt","r")


for line in feeds_to_parse:
    parser = fp.parse(str(line))
    x = len(parser['entries'])
    count = 0   
    while count < x:

现在我有几个解决方案。 起初,我试过这个:

cursor.execute("INSERT INTO feed (link, title, publication_date, newspaper) VALUES (%s, %s, %s, %s)",
        (parser['entries'][count]['link'], parser['entries'][count]['title'],
        parser['entries'][count]['published'],parser['feed']['title']))

但当然我有重复的数据。所以我在这里看到这篇文章: Avoiding duplicated data in PostgreSQL database in Python

我试过这个,但我的元组索引超出了范围错误

cursor.execute("""INSERT INTO feed (link, title, publication_date, newspaper) SELECT %s, %s, %s, %s WHERE NOT EXISTS
              (feed.title FROM feed WHERE feed.title=%s);""",
            (parser['entries'][count]['link'], parser['entries'][count]['title'],
            parser['entries'][count]['published'],parser['feed']['title']))

但无论如何,那不是我想要的方式。我想在我的while循环中添加一个条件,在插入之前测试数据的存在,因为我不想测试整个数据库,我只想测试最后的条目。再一次,当然它不起作用,因为我猜解析器[&#39;] [计数] [&#39;标题&#39;]不是我认为的......

while count < x:
    if parser['entries'][count]['title'] != cursor.execute("SELECT feed.title FROM feed WHERE publication_date > current_date - 15"):

cursor.execute("INSERT INTO feed (link, title, publication_date, newspaper) VALUES (%s, %s, %s, %s)",
        (parser['entries'][count]['link'], parser['entries'][count]['title'],
        parser['entries'][count]['published'],parser['feed']['title']))




conn.commit()

cursor.close()
conn.close()

1 个答案:

答案 0 :(得分:0)

您必须添加在where部分中使用的第二个标题,您还可以在其中添加额外条件:

cursor.execute(
    "INSERT INTO feed (link, title, publication_date, newspaper) "
    "SELECT %s, %s, %s, %s WHERE NOT EXISTS (SELECT 1 FROM feed "
    "WHERE title = %s AND publication_date > current_date - 15);",
    (parser['entries'][count]['link'],
     parser['entries'][count]['title'],
     parser['entries'][count]['published'],
     parser['feed']['title'],
     parser['feed']['title']))