解决:TypeError: write() argument must be str, not Tag

2023-12-13 04:57:07

解决:TypeError: write() argument must be str, not Tag





背景

在使用之前的代码时,报错:
Traceback (most recent call last):
File “E:/Test/test.py”, line 14, in
file.write(tag_str)
TypeError: write() argument must be str, not Tag



报错问题


Traceback (most recent call last):
  File "E:/Test/test.py", line 14, in <module>
    file.write(tag_str)
TypeError: write() argument must be str, not Tag



报错翻译

主要报错信息内容翻译如下所示:


Traceback (most recent call last):
  File "E:/Test/test.py", line 14, in <module>
    file.write(tag_str)
TypeError: write() argument must be str, not Tag

翻译:

追溯(最近一次通话):
文件“E:/Test/Test.py”,第14行,在中
file.write(tag_str)
TypeError:write()参数必须是str,而不是Tag



报错位置代码


...
        divs = html.xpath('//div[@class="rank"]//span[@class="span"]') 
        file.write(tag_str)
...



报错原因

经过查阅资料,发现是这个错误产生的原因是在代码中,试图使用写入(write)函数将一个Tag对象写入某个文件,但是write函数要求的参数必须是字符串,而不是Tag对象。然后这样的错误提示就是这么产生的。

小伙伴们按下面的解决方法即可解决!!!



解决方法

要解决这个错误,需要检查你代码,确保在调用write函数时传入的参数是一个字符串。例如,可以将Tag对象转换为字符串,然后再使用write函数写入文件,代码如下。

正确的代码是:


...
        tag_str = str(tag_object)
        file.write(tag_str) 

...

write()函数的官方文档内容如下:

write(fd, str)

Write the bytestring in str to file descriptor fd.

Return the number of bytes actually written.

Note This function is intended for low-level I/O and must be applied
to a file descriptor as returned by os.open() or pipe(). To write a
“file object” returned by the built-in function open() or by popen()
or fdopen(), or sys.stdout or sys.stderr, use its write() method.
Changed in version 3.5: If the system call is interrupted and the
signal handler does not raise an exception, the function now retries
the system call instead of raising an InterruptedError exception (see
PEP 475 for the rationale).

翻译如下:

write(fd, str)

将str中的字节串写入文件描述符fd。

返回实际写入的字节数。

注意:此函数用于低级I/O,必须应用于由os.open()或pipe()返回的文件描述符。编写由内置函数open()或popen()或fdopen()返回的“文件对象”。标准输出或系统。Stderr,使用其write()方法。
在3.5版更改:如果系统调用被中断,而信号处理程序没有引发异常,该函数现在会重试系统调用,而不是引发InterruptedError异常(原因请参阅PEP 475)。



今天的分享就到此结束了

欢迎点赞评论关注三连

在这里插入图片描述

文章来源:https://blog.csdn.net/nings666/article/details/134939645
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。