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

时间:2022-03-22 13:55:43

I modified an html file by removing some of the tags using beautifulsoup. Now I want to write the results back in a html file. My code:

我通过使用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)

Since I used soup.prettify, it generates html like this:

由于我使用了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>

I want to get the result like print i does:

我想得到像我打印的结果:

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

How can I get a result the same as print i (ie. so the tag and its content appear on the same line)? Thanks.

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

2 个解决方案

#1


25  

Just convert the soup instance to string and write:

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

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

#2


3  

Use unicode to be safe:

使用unicode是安全的:

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

#1


25  

Just convert the soup instance to string and write:

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

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

#2


3  

Use unicode to be safe:

使用unicode是安全的:

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