首页 > 解决方案 > RSS feedparser 到 MySQL 数据库未填充

问题描述

我在 Python 中使用 Feedparser 来收集 RSS 提要,然后使用 mysql.connector 将数据输入到我的数据库中。我一直在尝试很多不同的变化,但我遇到了一些障碍。

Feedparser 收集数据很好,我可以输出到文件或显示,但是当我尝试将其输入 MySQL 数据库时它不起作用,但也不会抛出任何错误消息。任何帮助将不胜感激。请在下面查看我的代码的最新迭代。

       import feedparser
       import mysql.connector

       RSS_in = feedparser.parse("https://examplewebsite.com/feed/") # RSS feed location

       for item in RSS_in['items']:

           title = item.title

           description = item.description

           content = item.content

           print(title)

           print(description)

           print(content)


        def save_feed(items):

            sql = "INSERT INTO RSS_news VALUES (%s, %s, %s)"

            con = mysql.connector.connect(user='username', password='password',  host='localhost',    database='databse_one') # Connection details for database

            with con:

                cur = con.cursor()

                for item in items:

                        cur.execute(format(sql % (item.title, item.description, item.content)))

            print('successful')

            con.commit()

            cur.close()


标签: pythonmysqlfeedparser

解决方案


参考:MySQL 插入语法

如果表中的列数多于我们要保存的数据属性数,请在insert statement.

sql = "INSERT INTO RSS_news (col1, col2, col3) VALUES (%s, %s, %s)"

替换col1, col2, col3为实际的数据库表字段名称。

多个插入Python MySQL - 在表中插入数据- 要一次插入多个,您可以使用executemany.

cur = con.cursor()
cur.executemany(sql, items)

推荐阅读