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

新手上路,请多包涵

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

原文由 Kim Hyesung 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.3k
2 个回答

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

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

原文由 alecxe 发布,翻译遵循 CC BY-SA 3.0 许可协议

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

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

原文由 andytham 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题