简体   繁体   中英

beautiful soup 4 print soup.find_all error

I tried to export the text from beautiful soup into a text file but it shows

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

This is my code

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

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

What's wrong?

From the 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>]

So, soup.find_all returns a list , but you need a string (a character buffer object).

Try the following:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM