UnicodeEncodeError: 'ascii' codec can't encode characters

时间:2021-06-05 20:19:39

将网页get到之后输入文本出现UnicodeEncodeError: 'ascii' codec can't encode characters错误

f = open('re.txt', 'w')
url = "http://www.baidu.com"
r = requests.get(url)
r.raise_for_status()
r.encoding = r.apparent_encodingprint(r.text)
f.write(r_text)
f.close()

解决办法是

  r_text = r.text.encode('UTF-8')

加入这一行