获得&在标题返回使用praw

时间:2013-11-03 23:11:26

标签: python reddit praw

我正在尝试使用praw获得给定subreddit的前25位:

import praw

subreddit = 'gamedeals'

r = praw.Reddit(user_agent='getting top 25 of all time by /u/sqrg')

submissions = r.get_subreddit(subreddit).get_top_from_all(limit=25)

titlesFile = open("text.txt", 'w')

for s in submissions:
    titlesFile.write(s.title.encode('utf-8', 'replace') + '\n')

titlesFile.close()

我得到一个UnicodeEncodeError:'ascii'编解码器无法对位置63中的字符u'\ xa3'进行编码:序数不在范围内(128)

所以我将for循环中的行改为:

titlesFile.write(s.title.encode('utf-8', 'replace') + '\n')

它有效,但在text.txt文件中,我得到“& amp;” (没有空格)而不是“&”。我可以用一些字符串替换功能来改变它们,但有没有办法直接写出正确的标题?另外,为什么我必须使用encode()方法?

1 个答案:

答案 0 :(得分:1)

启用设置以解码html实体:

r = praw.Reddit(user_agent='getting top 25 of all time by /u/sqrg')
r.config.decode_html_entities = True

配置文件文档:https://praw.readthedocs.org/en/latest/pages/configuration_files.html

此处有更多信息:https://github.com/praw-dev/praw/issues/186