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

Posted

技术标签:

【中文标题】如何使用 Python BeautifulSoup 将输出写入 html 文件【英文标题】:How to write the output to html file with Python BeautifulSoup 【发布时间】:2017-03-24 14:43:53 【问题描述】:

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

【问题讨论】:

【参考方案1】:

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

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

【讨论】:

如果您遇到编码问题,请使用此with open("output1.html", "w", encoding='utf-8') as file:【参考方案2】:

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

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

【讨论】:

【参考方案3】:

使用 unicode 是安全的:

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

【讨论】:

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

以上是关于如何使用 Python BeautifulSoup 将输出写入 html 文件的主要内容,如果未能解决你的问题,请参考以下文章

如何在 Python 中使用 Beautifulsoup 从 Indeed 搜索中获取所有招聘信息的 href?

如何使用python和beautifulsoup获取title属性?

如何使用Python中的BeautifulSoup从HTML链接解析嵌套表?

如何使用 BeautifulSoup 和 Python 调用 JavaScript 函数

如何解决'连接中止'。使用BeautifulSoup在Python中出错

如何使用 BeautifulSoup 从 JSON 数据制作 Python 字典