如何使用 Python BeautifulSoup 将输出写入 html 文件 [英] How to write the output to html file with Python BeautifulSoup
本文介绍了如何使用 Python BeautifulSoup 将输出写入 html 文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我通过使用 beautifulsoup
删除一些标签来修改一个 html 文件.现在我想将结果写回到一个 html 文件中.我的代码:
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:
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如下:
Since I used soup.prettify, it generates html like this:
<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
那样的结果:
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>
如何获得与 print i
相同的结果(即标签及其内容出现在同一行)?谢谢.
How can I get a result the same as print i
(ie. so the tag and its content appear on the same line)? Thanks.
推荐答案
只需将 soup
实例转换为字符串 并写入:
Just convert the soup
instance to string and write:
with open("output1.html", "w") as file:
file.write(str(soup))
这篇关于如何使用 Python BeautifulSoup 将输出写入 html 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文