我想自己构建一个RSS Feed阅读器。所以我开始了。
我的测试页面,从我获取Feed的位置是“http://heise.de.feedsportal.com/c/35207/f/653902/index.rss”。
这是一个德语页面,因为我选择解码“iso-8859-1”。所以这是代码。
def main():
counter = 0
try:
page = 'http://heise.de.feedsportal.com/c/35207/f/653902/index.rss'
sourceCode = opener.open(page).read().decode('iso-8859-1')
except Exception as e:
print(str(e))
#print sourceCode
try:
titles = re.findall(r'<title>(.*?)</title>',sourceCode)
links = re.findall(r'<link>(.*?)</link>',sourceCode)
except Exception as e:
print(str(e))
rssFeeds = []
for link in links:
if "rss." in link:
rssFeeds.append(link)
for feed in rssFeeds:
if ('html' in feed) or ('htm' in feed):
try:
print("Besuche " + feed+ ":")
feedSource = opener.open(feed).read().decode("iso-8859-1","replace")
except Exception as e:
print(str(e))
content = re.findall(r'<p>(.*?)</p>', feedSource)
try:
tempTxt = open("feed" + str(counter)+".txt", "w")
for line in content:
tempTxt.write(tagFilter(line))
except Exception as e:
print(str(e))
finally:
tempTxt.close()
counter += 1
time.sleep(10)
现在开始出现问题。我解码那些方面,仍然德国方面,我得到错误,如:
我真的不知道为什么它不起作用。 出现错误之前收集的数据将写入文本文件。
收集数据的示例:
Einloggen auf heise onlineTopthemen:Nachdem Google Anfang des Monats eine 64-Bit-Beta seines hauseigenen BrowsersChromefürWindows7 und Windows 8 vorgestellt hatte,kümmertichider Internetriese nun auch um OS X. Wie Tester melden,verbreitetGoogleüberseine Canary- / Dev-KanälefürEntwicklerund Early Adopter nun automatisch 64-Bit-Builds,用户übereeinen kompatiblenRechnerverfügt。
我希望有人可以帮助我。还欢迎其他有助于我建立自己的RSS提要阅读器的线索或信息。
Greetings Templum
答案 0 :(得分:2)
Per miko和Wooble的评论:
自返回的XML以来, iso-8859-1
应为utf-8
编码为utf-8
:
In [71]: sourceCode = opener.open(page).read()
In [72]: sourceCode[:100]
Out[72]: "<?xml version='1.0' encoding='UTF-8'?><?xml-stylesheet type='text/xsl' href='http://heise.de.feedspo"
你真的应该使用像lxml或BeautifulSoup这样的XML解析器来解析XML。仅使用re
模块更容易出错。
feedSource
是unicode
,因为它是解码的结果:
feedSource = opener.open(feed).read().decode("utf-8","replace")
因此,line
也是unicode
:
content = re.findall(r'<p>(.*?)</p>', feedSource)
for line in content:
...
tempTxt
是一个纯文件句柄(与使用io.open
打开的句柄相对,它采用编码参数)。因此tempTxt
需要字节(例如str
),而不是unicode
。
在写入文件之前编码line
:
for line in content:
tempTxt.write(line.encode('utf-8'))
或使用tempTxt
定义io.open
并指定编码:
import io
with io.open(filename, "w", encoding='utf-8') as tempTxt:
for line in content:
tempTxt.write(line)
顺便说一句,除非你准备好处理所有异常,否则捕获所有异常并不好:
except Exception as e:
print(str(e))
此外,如果您只打印错误消息,那么Python可能会执行后续代码,即使try
部分中定义的变量未定义。例如,
try:
print("Besuche " + feed+ ":")
feedSource = opener.open(feed).read().decode("iso-8859-1","replace")
except Exception as e:
print(str(e))
content = re.findall(r'<p>(.*?)</p>', feedSource)
如果在定义feedSource
之前引发了异常,则在调用re.findall
时使用feedSource
可能会引发NameError。
如果您希望Python传递此continue
并转到下一个{<1}},您可能需要在except-suite
中添加feed
语句:
except Exception as e:
print(str(e))
continue