Python3写入文件BeautifulSoup

3

我希望能够使用以下代码编写beautifulsoup表单:

soup = BeautifulSoup(con.content)
f = open('/*/*/Desktop/littletext.rtf','w')
f.write(str(soup))
f.close()

我遇到了这个错误:

Traceback (most recent call last): File "///Desktop/test123.py", line 10, in f.write(soup) TypeError: 必须是字符串,不能是BeautifulSoup

有什么办法可以解决吗?我尝试将'soup'转换为字符串,但没有成功 -- f.write(str(soup))。


1
你问题顶部的代码与追踪回溯不匹配。"没有起作用"的意思是什么?你实际上使用f.write(str(soup))时得到了什么错误信息? - jonrsharpe
@jonrsharpe 追踪回溯(最近的调用在前): 文件 "///Desktop/test123.py",第10行,在<module>中: f.write(str(soup)) UnicodeEncodeError: 'ascii' 编解码器无法将字符 '\u2026' 编码到位置28521:超出范围(128)的序数。 - Bob Ebert
所以你已经阅读了关于处理UnicodeEncodeError或Python中的Unicode的众多现有问题的任何一个,或者例如https://docs.python.org/3/howto/unicode.html吗? - jonrsharpe
1个回答

16

我发现我的问题在于我需要在代码中使用'wb'

f = open('/*/*/Desktop/littletext.rtf','wb')

f.write(str(soup))

必须是

f.write(soup.encode('utf-8'))

1
感谢这个简单明了的解决方案! - Vivian

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接