如何在 Python 中使用 BeautifulSoup 保存对 HTML 文件所做的更改? [英] How to save back changes made to a HTML file using BeautifulSoup in Python?

查看:12
本文介绍了如何在 Python 中使用 BeautifulSoup 保存对 HTML 文件所做的更改?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有下面的脚本,它修改 HTML 文件中的 href 属性(将来,它将是目录中的 HTML 文件列表).使用 BeautifulSoup,我设法访问标签值并按照我的需要修改它们,但我不知道如何保存对文件所做的更改.

I have the script below, which modifies href attributes in an HTML file (in the future, it will be a list of HTML files in a directory). Using BeautifulSoup I managed to access the tag values and modify them like I want, but I don't know how to save back the changes made to the file.

import os
import re
from bs4 import BeautifulSoup


htmlDoc = open('adding_computer_c.html',"r+")
soup = BeautifulSoup(htmlDoc)

replacements= [ ('_', '-'), ('../tasks/', prefixUrl), ('../concepts/', prefixUrl) ]

for link in soup.findAll('a', attrs={'href': re.compile("../")}):


    newlink=str(link)

    for k, v in replacements:

        newlink = newlink.replace(k, v)

    extrachars=newlink[newlink.find("."):newlink.find(">")]
    newlink=newlink.replace(extrachars,'')


    link=newlink
    print(link)
    ##How do I save the link I have modified back to the HTML file?

print(soup)##prints the original html tree

htmlDoc.close()

推荐答案

newlink = link['href']
# .. make replacements
link['href'] = newlink # store it back

现在 print(soup.prettify()) 将显示更改的链接.将更改保存到文件:

Now print(soup.prettify()) will show changed links. To save the changes to a file:

htmlDoc.close()

html = soup.prettify("utf-8")
with open("output.html", "wb") as file:
    file.write(html)

要保留文档的原始字符编码,您可以使用 soup.original_encoding 而不是utf-8".请参阅编码.

To preserve original character encoding of the document, you could use soup.original_encoding instead of "utf-8". See Encodings.

这篇关于如何在 Python 中使用 BeautifulSoup 保存对 HTML 文件所做的更改?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆