Skip to main content
 首页 » 编程设计

python之使用 PRAW 在标题返回中获取 & 而不是 &

2025年05月04日11bonelee

我正在尝试使用 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' codec can't encode character u'\xa3' in position 63: ordinal not in range(128)

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

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

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

请您参考如下方法:

启用设置以解码 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