使用 feedparser、MySQldb 和 python 将 rss 提要图像插入 mysql 数据库

inserting rss feed images into mysql database with feedparser, MySQldb and python

我能够解析 RSS 提要并将链接、图块和描述成功保存到我的数据库中,但是当我尝试对同一提要中的图像执行相同操作时,出现错误。我已经检查过 xml 文件是否有类别 'image' 可以通过以下方式使用:

d.feed.image {'subtitle': u'SABC News', 'links': [{'href': u'http://www.sabc.co.za/news/', 'type': u'text/html', 'rel': u'alternate'}], 'title': u'SABC News', 'height': 173, 'width': 308, 'title_detail': {'base': u'http://www.sabc.co.za/SABC/RSS/news/TopStoryRSSFeed.xml', 'type': u'text/plain', 'value': u'SABC News', 'language': None}, 'href': u'http://www.sabc.co.za/wps/PA_News/images/newslogo2.jpg', 'link': u'http://www.sabc.co.za/news/', 'subtitle_detail': {'base': u'http://www.sabc.co.za/SABC/RSS/news/TopStoryRSSFeed.xml', 'type': u'text/html', 'value': u'SABC News', 'language': None}}

但是当我尝试将它保存到我的数据库时,我得到这个错误:

Traceback (most recent call last):
 File "C:/Users/les/Desktop/rss2.py", line 18, in <module>
cursor.execute("""INSERT INTO zed (title, description, link, image) VALUES    
(%s,%s,%s,%s)""", (d.entries[i].title, d.entries[i].description,   
d.entries[i].link, d.entries[i].image))
File "C:\Python27\lib\site-packages\feedparser.py", line 416, in __getattr__
raise AttributeError, "object has no attribute '%s'" % key
AttributeError: object has no attribute 'image'

我使用的代码如下:

import feedparser, MySQLdb

我设置了与 MySQL 数据库的连接

db = MySQLdb.connect(host='localhost',user='root',passwd='',db='rss')

cursor=db.cursor()

获取 feed 并转化为 feedparser 对象

d=feedparser.parse('http://www.sabc.co.za/SABC/RSS/news/TopStoryRSSFeed.xml')

确定提要中的条目数,用于处理循环

x = len(d.entries)

处理循环 - 对于每个条目,选择某些属性并将它们插入 MySQL table。还将 RSS 条目日期转换为 MySQL 日期

for i in range(x):
    d2 = d.entries[i].description
    cursor.execute("""INSERT INTO zed (title, description, link, image)   
    VALUES (%s,%s,%s,%s)""", (d.entries[i].title, d.entries[i].description,   
    d.entries[i].link, d.entries[i].image))

db.commit()

他可能是什么问题?

我认为你应该更换

d.entries[i].image

d.entries[i].links[1].href