我使用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
相同的结果(即标签及其内容出现在同一行)?感谢。
答案 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))