My code is below. This is code for parsing links from urls. I have dictonary of 2 urls:
newsurls = {'Kommersant': 'https://www.kommersant.ru/RSS/news.xml',
'Vesti': 'https://www.vesti.ru/vesti.rss'}
class News:
def __init__(self, rss_dict):
self.rss_dict = rss_dict
self.parseRSS()
self.get_links()
def parseRSS(self):
for key, url in self.rss_dict.items():
return feedparser.parse(url)
def get_links(self):
allfeed = []
for key, url in newsurls.items():
feed = News.parseRSS(self)
allfeed.extend(feed)
links = []
alllinks = []
for newsitem in allfeed['items']:
links.append(newsitem['link'])
for key, url in self.rss_dict.items():
alllinks.extend(links)
self.alllinks = alllinks
for l in alllinks:
print(l)
News(newsurls)
I have error TypeError: list indices must be integers or slices, not str
in line for newsitem in allfeed['items']:
i think i have problem cause it's list
of dictonaries
, how can i optimize this code?
TypeError Traceback (most recent call last)
<ipython-input-43-7e99e79bbd4b> in <module>()
----> 1 News(newsurls)
<ipython-input-42-a003b05ebeb5> in __init__(self, rss_dict)
3 self.rss_dict = rss_dict
4 self.parseRSS()
----> 5 self.get_links()
6
7
<ipython-input-42-a003b05ebeb5> in get_links(self)
22 alllinks = []
23
---> 24 for newsitem in allfeed['items']:
25 links.append(newsitem['link'])
26
TypeError: list indices must be integers or slices, not str
The reason you are getting this is error is because allfeed
is a list as defined on line 17 ( allfeed = []
). To fix it simply replace
for newsitem in allfeed['items']:
with
for newsitem in allfeed:
It's a bit hard to make sense of what you're trying to do, but I think it's this:
links = []
for key, url in self.rss_dict.items():
feed = feedparser.parse(url)
for newsitem in feed['items']:
links.append(newsitem['link'])
alllinks = []
for newsitem in allfeed['items']:
above are culprit lines, either defined
alllinks = {}
or use
for newsitem in allfeed
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.