【发布时间】:2017-06-05 19:00:51
【问题描述】:
我一直在使用 python 编写 XML 解析器,我将新闻网站的 RSS 提要作为输入。我实现了一个 loadRSS() 函数,我在特定提要的 url 上使用了 requests.get()。我的代码
def loadRSS(src,filename):
resp = requests.get(src)
#print resp.content
with open(filename, 'wb') as f:
f.write(resp.content)
现在我根据新闻的不同部分有各种子目录,每个子目录都有各自的 RSS 提要 url,所以有体育、科学等文件夹,每个文件夹都有一个 source.txt 文件,其中有相应的 url RSS订阅。我正在使用 os.walk() 遍历每个文件
for root, sub, f in os.walk(rootdirectory):
for f1 in f:
if f1=='source.txt':
src=""
with open(os.path.join(root,f1),'r') as f2:
src=f2.readline()
loadRSS(src,os.path.join(root,"topnewsfeed.xml"))
newsitems = parseXML(os.path.join(root,"topnewsfeed.xml"))
savetoCSV(newsitems,os.path.join(root,"topnews.csv"))
运行脚本时出现错误
xml.etree.ElementTree.ParseError: not well-formed (invalid token): line 22, column 311
所以我决定检查由 loadRSS() 函数形成的 xml 文件。令我惊讶的是,正在为不同的 RSS 提要获取不同类型的数据(即使我使用相同的逻辑将数据放在 xml 文件中)。例如,'Hindustan Times'的topnews/rssfeed.xml对应的RSS feed(抱歉,我没有足够的声誉,无法发布所有链接),xml文件是根据页面来源完美形成的。但是对于另一个 RSS 链接http://timesofindia.indiatimes.com/rssfeeds/1081479906.cms,我得到了一个不稳定的xml file on my system
这与该 RSS 页面的 xml 不相符。我已经非常努力地调试它,但仍然不知道可能导致它的原因以及如何纠正它,这是一个很大的刺激原因。任何帮助,将不胜感激。谢谢
【问题讨论】: