如何使用Python中的BeautifulSoup保存对HTML文件所做的更改?

Pep*_*oyd 17 python beautifulsoup html-parsing

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

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()
Run Code Online (Sandbox Code Playgroud)

jfs*_*jfs 38

newlink = link['href']
# .. make replacements
link['href'] = newlink # store it back
Run Code Online (Sandbox Code Playgroud)

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

htmlDoc.close()

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

要保留文档的原始字符编码,可以使用soup.original_encoding"utf-8"代替.见编码.

  • 对于 Python 3,您必须使用:`open("output.html", "wt")` (2认同)
  • @BrunoGabuzomeu 错了。`soup.prettify('utf-8')` 返回字节,因此必须使用 'wb',如答案中所示。 (2认同)