如何使用Python BeautifulSoup将输出写入html文件

时间:2016-11-10 14:21:32

标签: python html beautifulsoup

我使用beautifulsoup删除了一些标记来修改html文件。现在我想将结果写回html文件中。 我的代码:

from bs4 import BeautifulSoup
from bs4 import Comment

soup = BeautifulSoup(open('1.html'),"html.parser")

[x.extract() for x in soup.find_all('script')]
[x.extract() for x in soup.find_all('style')]
[x.extract() for x in soup.find_all('meta')]
[x.extract() for x in soup.find_all('noscript')]
[x.extract() for x in soup.find_all(text=lambda text:isinstance(text, Comment))]
html =soup.contents
for i in html:
    print i

html = soup.prettify("utf-8")
with open("output1.html", "wb") as file:
    file.write(html)

由于我使用了soup.prettify,它会生成如下的html:

<p>
    <strong>
     BATAM.TRIBUNNEWS.COM, BINTAN
    </strong>
    - Tradisi pedang pora mewarnai serah terima jabatan pejabat di
    <a href="http://batam.tribunnews.com/tag/polres/" title="Polres">
     Polres
    </a>
    <a href="http://batam.tribunnews.com/tag/bintan/" title="Bintan">
     Bintan
    </a>
    , Senin (3/10/2016).
   </p>

我想得到像print i那样的结果:

<p><strong>BATAM.TRIBUNNEWS.COM, BINTAN</strong> - Tradisi pedang pora mewarnai serah terima jabatan pejabat di <a href="http://batam.tribunnews.com/tag/polres/" title="Polres">Polres</a> <a href="http://batam.tribunnews.com/tag/bintan/" title="Bintan">Bintan</a>, Senin (3/10/2016).</p>
<p>Empat perwira baru Senin itu diminta cepat bekerja. Tumpukan pekerjaan rumah sudah menanti di meja masing masing.</p>

如何获得与print i相同的结果(即标签及其内容出现在同一行)?感谢。

3 个答案:

答案 0 :(得分:34)

只需soup实例转换为字符串并写入:

with open("output1.html", "w") as file:
    file.write(str(soup))

答案 1 :(得分:7)

使用unicode是安全的:

with open("output1.html", "w") as file:
    file.write(unicode(soup))

答案 2 :(得分:0)

对于Python 3,unicode被重命名为str,但是我确实必须传递编码参数来打开文件以避免UnicodeEncodeError

with open("output1.html", "w", encoding='utf-8') as file:
    file.write(str(soup))