如何在文本文件中将输出复制到 BS4 中的终端

how to duplicate output to terminal in bs4 in text file

提问人:topplethepat 提问时间:12/8/2018 最后编辑:topplethepat 更新时间:12/8/2018 访问量:31

问:

我是第一次使用 bs4。如果我使用这个基本代码:

from bs4 import BeautifulSoup
with open ('test.txt','r') as f:
    soup = BeautifulSoup(f)
    print f

终端中的输出非常干净,不包含 HTML 标签。如果我尝试将其打印到 txt 文件,它会提示我添加解析器,所以我添加了“html.parser”。我没有得到相同的结果,即它充满了我试图摆脱的标签。如何在 txt 文件中获得相同的结果?

from bs4 import BeautifulSoup
with open ('test.txt','r') as f:
    soup = BeautifulSoup(f,'html.parser')
    with open ('test2.txt', 'w') as x:
        x.write(str(soup))

*编辑 这是我运行此代码时 test2.txt 中的内容示例:

    each\u00a0row you want to accept.\n <li>At the top of the list, 
    under the <b>Batch Actions</b> drop-down arrow, 
    choose\u00a0<b>Accept Selected</b>.</li>\n <li>All the selected 
    transactions\u00a0move from the <b>For Review

但是在终端中,我得到:

    each\u00a0row you want to accept.\n At the top of the list, under 
    the Batch Actions drop-down arrow, choose\u00a0Accept Selected.\n 
    All the selected transactions\u00a0move from the For Review 
    tab\u00a0to the In QuickBooks 
python-2.7 beautifulsoup html解析

评论

0赞 wpercy 12/8/2018
你能分享一下test.txt的一些内容吗?

答:

1赞 chitown88 12/8/2018 #1

尝试添加属性.text

x.write(str(soup.text))