简体   繁体   中英

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

i am able to parse an rss feed and save the links, tiles and description to my database successfully, however when i try to do the same for images in the same feed, i'm getting an error. I already checked if the xml file has the category 'image' to work with via:

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}}

but when i try to save it to my database, I get this error:

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'

the code i'm using is the following:

import feedparser, MySQLdb

I set up connection to MySQL database

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

cursor=db.cursor()

fetch feed and turn into feedparser object

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

determine number of entries in feed, which is used in processing loop

x = len(d.entries)

processing loop - for each entry, selects certain attributes and inserts them into a MySQL table. Also converts the RSS entry date into a MySQL date

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()

what could be he problem?

I think you should replace

d.entries[i].image

with

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM