如何在Twitter Bot中转换HTML实体字符?
解决Twitter Bot中圣经经文HTML实体转换问题
你遇到的问题是API返回的经文包含HTML实体(比如é、ó这类),需要把这些实体转换成对应的普通字符。Python标准库中的html模块就能轻松处理这个需求,用html.unescape()方法即可完成解码。
修改后的代码如下:
import tweepy import requests import html # 引入html模块 api = tweepy.Client( consumer_key='', consumer_secret='', access_token='-', access_token_secret='', ) response = requests.get("https://www.biblegateway.com/votd/get/?format=json&version=NVI-PT") verse_of_the_day = response.json()["votd"]["text"] # 解码HTML实体 decoded_verse = html.unescape(verse_of_the_day) try: tweet=api.create_tweet(text=("Aqui está o versículo do dia: \n") + decoded_verse) print(tweet) except Exception as e: # 捕获异常并打印具体信息,方便调试 print(f"出错了: {e}")
另外把原来的except:改成except Exception as e,能打印具体错误信息,对你调试问题更有帮助。
内容的提问来源于stack exchange,提问作者Luis
相关产品推荐
相关产品推荐

