【问题标题】:beautiful soup 4 print soup.find_all error美丽的汤4打印soup.find_all错误
【发布时间】:2015-04-18 22:57:19
【问题描述】:

我试图将美丽汤中的文本导出到文本文件中,但它显示了

"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) 

怎么了?

【问题讨论】:

  • 这个错误全是expected a character buffer objectimportant 是一个不是字符缓冲区对象的对象。

标签: python beautifulsoup


【解决方案1】:

来自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 返回一个list,但你需要一个字符串(一个字符缓冲区对象)。

尝试以下方法:

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

【讨论】:

  • 谢谢。它返回“ text_file2.write(x+'\n') TypeError: unsupported operand type(s) for +: 'Tag' and 'str' ”这是否意味着我的 soup.find_all 返回了一个标签?
  • @user3396218,请重新加载页面:我已经对我的帖子进行了编辑。
  • 谢谢。设法打印出文本文件。但里面什么都没有。我认为这可能是由于我使用美丽的汤获取数据时出错。现在我要解决那个问题。再次感谢!
  • @user3396218,尝试打印important 变量的值。如果它是空的,那么文件也将是空的
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多