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

Kim*_*ung 28 html python beautifulsoup

我通过删除一些标签修改了一个html文件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)
Run Code Online (Sandbox Code Playgroud)

由于我使用了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>
Run Code Online (Sandbox Code Playgroud)

我希望得到的结果如下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>
Run Code Online (Sandbox Code Playgroud)

我怎样才能得到相同的结果print i(即标签及其内容出现在同一行)?谢谢.

ale*_*cxe 42

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

with open("output1.html", "w") as file:
    file.write(str(soup))
Run Code Online (Sandbox Code Playgroud)

  • 如果遇到编码问题,请使用“with open("output1.html", "w",encoding='utf-8') as file:` (8认同)

小智 18

对于 Python 3,unicode已重命名为str,但我确实必须传入 encoding 参数以打开文件以避免UnicodeEncodeError.

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


spe*_*edy 8

使用unicode是安全的:

with open("output1.html", "w") as file:
    file.write(unicode(soup))
Run Code Online (Sandbox Code Playgroud)

  • 为了未来读者的利益,正如 @andytham 提到的,您只能对 Python 2 使用 `unicode()`;对于 Python 3 使用 `str()` 代替 (3认同)