脚本仅向postgres数据库输入最后一个值

时间:2019-05-30 16:41:01

标签: python postgresql psycopg2

Python的新手。我正在尝试从RSS提要中获取数据,解析数据,然后将数据插入数据库。我的一小段代码获取了正确的项目,我可以打印结果,但是我只能获取RSS feed中的最后一个项目才能发布到数据库中。我相信我可能错误地定义了“ html”和“ link”。我希望item.title和item.link填充一个列表,然后以正确的顺序输入到数据库中。任何帮助表示赞赏。

import sys
import requests
import urllib2
import feedparser
import psycopg2
import psycopg2.extras
from psycopg2.extras import execute_values
import time

url = "https://www.ferc.gov/xml/whats-new.xml"
response = urllib2.urlopen(url).read()


#saving the xml file
response = requests.get(url)
#with open('whats_hot.xml', 'wb') as file:
#    file.write(response.content)


d = feedparser.parse('https://www.ferc.gov/xml/whats-new.xml')


for item in d.entries:
    print "------"
    print item.published
    print item.title
    print item.link
    html = item.published + item.title
    link = item.link



con = psycopg2.connect(database="xx", 
user="xx", password="xx", host="127.0.0.1", 
port="5432")  
print("Database opened successfully")

cur = con.cursor()



#try:
psycopg2.extras.execute_values(cur,
"insert into ferc_hots (link,html) values %s",
      [(link,html)])
#except psycopg2.IntegrityError:
#     print 'Duplicate values found.  Insert was not successful'

con.commit()  
print("Records inserted successfully")  
con.close()

3 个答案:

答案 0 :(得分:1)

您的插入语句也必须位于for循环内。否则,您只插入最后一条记录。

con = psycopg2.connect(database="xx", 
user="xx", password="xx", host="127.0.0.1", 
port="5432")  
print("Database opened successfully")

cur = con.cursor()

for item in d.entries:
    print "------"
    print item.published
    print item.title
    print item.link
    html = item.published + item.title
    link = item.link
    psycopg2.extras.execute_values(cur,"insert into ferc_hots (link,html) values %s",[(link,html)])

con.commit()  
print("Records inserted successfully")  
con.close()

另一种选择是保存记录列表,并将它们插入到末尾。

答案 1 :(得分:0)

execute_values的参数列表必须是“序列序列”。这是一个列表列表(或元组列表)。就您而言,您只将最终商品的值保留在htmllink中,因此只提供了一个商品。

您会想要这样的东西:

args = []
for item in d.entries:
    print "------"
    print item.published
    print item.title
    print item.link
    args.append([item.published + item.title, item.link])

或者一口气:

args = [[item.published + item.title, item.link] for item in d.entries]

然后插入内容类似于:

psycopg2.extras.execute_values(cur,
          "insert into ferc_hots (link,html) values %s",
          args)

答案 2 :(得分:0)

html和link只是单个字符串值。它们在您的循环中不断变化,但是到您插入时,它们只是具有最后给出的值。您需要保留将要传递到插入内容的值元组的列表。注意,双括号是因为将元组附加到值列表中。元组的定义类似于(项目,项目),因此您要追加(项目,项目),而不仅仅是项目。

values = []
for item in d.entries:
    print "------"
    print item.published
    print item.title
    print item.link
    values.append((item.link, item.published + item.title))

...

psycopg2.extras.execute_values(cur,
    "insert into ferc_hots (link,html) values %s",
        values)