文章内容

2020/12/24 18:10:33,作 者: 黄兵

TypeError: write() argument must be str, not BeautifulSoup

最近在使用BeautifulSoup处理页面的内容,将内容保存到文件,出现如下错误:

TypeError: write() argument must be str, not BeautifulSoup

具体代码如下:

def save_country_flag_svg_file(self):
get_flag_uri = self.get_country_flag_uri(IP_STACK_URI)
conn = connection.ProcessConnection()
if get_flag_uri:
for item in get_flag_uri:
svg_code = conn.init_connection(item[0])
get_svg_path = os.path.join(os.getcwd(), f'files\\svg\\{item[1]}_flag.svg')
with open(get_svg_path, 'a') as svg_file:
svg_file.write(svg_code)

这里直接是写文件,采用字符串的方式写。

出现问题的原因:

但是这里写的文件是一个BeautifulSoup类型的,所以出现了如上错误。

解决方案:

改成二进制的方式写文件,关于wb的方式写文件,详细介绍如下:

当以二进制模式写入时,Python在写入文件时不会对数据进行任何更改。但是,在文本模式下(bw在用或指定文本模式时排除wt),Python将基于默认文本编码对文本进行编码。此外,Python会将行尾(\n转换为特定于平台的行尾,这会破坏二进制文件(例如exepng文件)。

因此,在编写文本文件时(无论使用纯文本还是基于文本的格式,如CSV)都应使用文本模式,而在编写非文本文件(如图像)时必须使用二进制模式。

修改代码如下:

def save_country_flag_svg_file(self):
get_flag_uri = self.get_country_flag_uri(IP_STACK_URI)
conn = connection.ProcessConnection()
if get_flag_uri:
for item in get_flag_uri:
svg_code = conn.init_connection(item[0])
get_svg_path = os.path.join(os.getcwd(), f'files\\svg\\{item[1]}_flag.svg')
with open(get_svg_path, 'wb') as svg_file:
svg_file.write(svg_code.encode('utf-8'))

最终问题解决。


参考资料:

1、What does 'wb' mean in this code, using Python?

2、Python3 Write to file beautifulsoup


黄兵个人博客原创。

转载请注明出处:黄兵个人博客 - TypeError: write() argument must be str, not BeautifulSoup

分享到:

发表评论

评论列表

user-ico

支持一个 on 回复 有用(0

支持一个

游客m)+v on 2020-12-31 15:41:11

博主回复:感谢支持。