簡體   English   中英

如何使用Python BeautifulSoup將輸出寫入html文件

[英]How to write the output to html file with Python 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相同的結果(即標簽及其內容出現在同一行)? 謝謝。

只需soup實例轉換為字符串並寫入:

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

使用unicode是安全的:

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

對於Python 3, unicode被重命名為str ,但我必須傳入encoding參數來打開文件以避免UnicodeEncodeError

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM