【问题标题】:how to resolve UnicodeEncodeError while converting to str如何在转换为 str 时解决 UnicodeEncodeError
【发布时间】:2020-11-22 11:43:20
【问题描述】:

这是我的代码

import requests as re
from bs4 import BeautifulSoup as bs
r = re.get("https://skidlamer.github.io/js/Skidfest.user.js")
soup = bs(r.text,"lxml")

with open("script.txt","w") as file:
    file.write(soup)

这是我遇到的错误

File "C:\Users\Anonymouse\AppData\Local\Programs\Python\Python37\lib\encodings\cp1252.py", line 19, in encode
    return codecs.charmap_encode(input,self.errors,encoding_table)[0]
UnicodeEncodeError: 'charmap' codec can't encode character '\U0001f4a9' in position 38190: character maps to <undefined>

【问题讨论】:

  • 你确定这个错误来自上面的代码吗?代码在file.write(soup) 早期失败。
  • 您想写入文件的具体内容是什么?的HTML?您想以二进制模式打开文件。试试with open("script.txt","wb") as file:
  • 当我在 ubuntu 中运行上面的代码时,它会显示 TypeError: write() argument must be str, not BeautifulSoup。将汤对象转换为 str 之后。它的工作。

标签: python-3.x beautifulsoup python-requests


【解决方案1】:

在将漂亮的汤对象转换为 str 类型后,我添加了 .encode("utf-8") 并且它起作用了

【讨论】:

    猜你喜欢
    • 2013-03-01
    • 2018-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-02
    • 2014-04-03
    • 2019-11-18
    相关资源
    最近更新 更多