问题解决:TypeError: write() argument must be str, not BeautifulSoup

执行程序时出现错误,原因是文件写入要求为str数据,而实际是BeautifulSoup类型。解决办法是将BeautifulSoup转化成str格式。

问题


with open('{}\{}.html'.format(HTML_PATH, certainty_detail_name), 'w', encoding='UTF-8') as fp:
    fp.write(soup)
    print("成功写入{}.html文件。".format(certainty_detail_name))

执行这个程序出现错误

Traceback (most recent call last):
  File "D:/PyDate/Climb_C_site/Get_C_Site.py", line 447, in <module>
    GetArticle().get_current_link(url)
  File "D:/PyDate/Climb_C_site/Get_C_Site.py", line 243, in get_current_link
    fp.write(soup)
TypeError: write() argument must be str, not BeautifulSoup

原因

文件写入的是str数据,而不是BeautifulSoup

解决

只需要将BeautifulSoup转化成str格式就成。

更改后:

with open('{}\{}.html'.format(HTML_PATH, certainty_detail_name), 'w', encoding='UTF-8') as fp:
    fp.write(str(soup))
    print("成功写入{}.html文件。".format(certainty_detail_name))

在 Python 中,`write()` 方法要求传入的参数是字符串(`str`)类型,而不是字节(`bytes`)类型。当在 `threading` 相关操作里使用 `write()` 方法时出现 `TypeError: write() argument must be str, not bytes` 错误,可参考以下解决办法: ### 以二进制模式打开文件 在 Python 3 里,`open()` 函数的 `encoding` 参数默认值为 `utf-8`,这使得读写文件时只能用 Unicode 编码的字符,不能使用二进制字符。所以可以用 `wb` 或者 `rb` 的方式打开文件,这样就能进行文件读写。示例代码如下: ```python import threading def write_to_file(): filename = 'test.txt' data = b'Hello, World!' # 字节数据 with open(filename, "wb") as f: f.write(data) # 创建并启动线程 thread = threading.Thread(target=write_to_file) thread.start() thread.join() ``` ### 对字节数据进行解码 若要以文本模式打开文件,那就需要把字节数据解码成字符串。示例代码如下: ```python import threading def write_to_file(): filename = 'test.txt' data = b'Hello, World!' # 字节数据 decoded_data = data.decode('utf-8') # 解码为字符串 with open(filename, "w") as f: f.write(decoded_data) # 创建并启动线程 thread = threading.Thread(target=write_to_file) thread.start() thread.join() ``` ### 修改代码中写入的参数 若在某些库文件里出现该错误,可修改代码,把传入 `write()` 方法的字节数据转换为字符串。例如在修改 `HTMLTestRunner.py` 文件时,将 `self.stream.write(output.encode('utf8'))` 修改为 `self.stream.write(output)` [^2][^4]。
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值