美汤4打印soup.find_all错误

beautiful soup 4 print soup.find_all error

我试图将 beautiful soup 中的文本导出到文本文件中,但它显示

"text_file2.write(important) 
TypeError: expected a character buffer object"

这是我的代码

important=soup.find_all("tr", class_="accList")

with open("important.txt","w") as text_file2:
    text_file2.write(important) 

怎么了?

来自docs

soup.find_all('a')
# [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>,
#  <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>,
#  <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]

所以,soup.find_all returns一个list,但是你需要一个字符串(一个字符缓冲对象)。

尝试以下操作:

with open("important.txt","w") as text_file2:
    for x in important:
        text_file2.write(str(x)+'\n')