我需要将页面cnn rss(http://rss.cnn.com/rss/edition.rss)转换为XML文件。我需要使用标签过滤:title,link和pubDate,然后将结果导出到csv文件。
我尝试了一段代码,但没有成功,因为结果省略了pubDate。
我使用此代码:
# Python code to illustrate parsing of XML files
# importing the required modules
import csv
import requests
import xml.etree.ElementTree as ET
def loadRSS():
# url of rss feed
url = 'http://rss.cnn.com/rss/edition.rss'
# creating HTTP response object from given url
resp = requests.get(url)
# saving the xml file
with open('topnewsfeed.xml', 'wb') as f:
f.write(resp.content)
def parseXML(xmlfile):
# create element tree object
tree = ET.parse(xmlfile)
# get root element
root = tree.getroot()
# create empty list for news items
newsitems = []
# iterate news items
for item in root.findall('./channel/item'):
# empty news dictionary
news = {}
# append news dictionary to news items list
newsitems.append(news)
# return news items list
return newsitems
def savetoCSV(newsitems, filename):
# specifying the fields for csv file
fields = ['title', 'pubDate', 'description', 'link', 'media']
# writing to csv file
with open(filename, 'w') as csvfile:
# creating a csv dict writer object
writer = csv.DictWriter(csvfile, fieldnames=fields)
# writing headers (field names)
writer.writeheader()
# writing data rows
writer.writerows(newsitems)
def main():
# load rss from web to update existing xml file
loadRSS()
# parse xml file
newsitems = parseXML('topnewsfeed.xml')
# store news items in a csv file
savetoCSV(newsitems, 'topnews.csv')
if __name__ == "__main__":
# calling main function
main()
我尝试配置参数,结果如下:
CNN将rss显示为web格式而不是xml,例如reddit:
如何获取此信息的任何想法?
答案 0 :(得分:1)
您提到的RSS Feed的XML条目为pubdate
,而不是pubDate
且资本为D.
如果问题是没有包含pubdate,那可能是问题的一部分。