如何使用 Python BeautifulSoup 将输出写入 html 文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40529848/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to write the output to html file with Python BeautifulSoup
提问by Kim Hyesung
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 文件中。我的代码:
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:
我想得到这样的结果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>
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
(即标签及其内容出现在同一行)相同的结果?谢谢。
回答by alecxe
Just convert the soup
instance to stringand write:
只需将soup
实例转换为字符串并写入:
with open("output1.html", "w") as file:
file.write(str(soup))
回答by andytham
For Python 3, unicode
was renamed to str
, but I did have to pass in the encoding argument to opening the file to avoid an UnicodeEncodeError
.
对于 Python 3,unicode
已重命名为str
,但我确实必须传入 encoding 参数以打开文件以避免UnicodeEncodeError
.
with open("output1.html", "w", encoding='utf-8') as file:
file.write(str(soup))
回答by spedy
Use unicode to be safe:
使用 unicode 是安全的:
with open("output1.html", "w") as file:
file.write(unicode(soup))