【发布时间】:2015-03-12 00:44:59
【问题描述】:
我能够解析 rss 提要并成功地将链接、图块和描述保存到我的数据库中,但是当我尝试对同一提要中的图像执行相同操作时,出现错误。我已经通过以下方式检查了 xml 文件是否具有“图像”类别:
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'@ 987654325@', 'type': u'text/html', 'value': u'SABC News', 'language': 无}}
但是当我尝试将它保存到我的数据库时,我收到了这个错误:
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 表中。还将 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()
他可能有什么问题?
【问题讨论】:
-
>>> print d.entries[0].keys() ['summary_detail', 'published_parsed', 'subcategory', 'links', 'title', 'tags', 'summary' , 'guidislink', 'title_detail', 'link', 'source', 'published', 'id'] “图片”在哪里?
-
@murali' 是不是? href': u'sabc.co.za/wps/PA_News/images/newslogo2.jpg',
-
我认为您应该将“d.entries[i].image”替换为“d.entries[i].links[1].href”并尝试
-
行得通!谢谢@Murali
标签: python mysql rss mysql-python feedparser