簡體   English   中英

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

[英]How to save back changes made to a HTML file using BeautifulSoup in Python?

我有下面的腳本,它修改HTML文件中的href屬性(將來,它將是目錄中的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()
newlink = link['href']
# .. make replacements
link['href'] = newlink # store it back

現在print(soup.prettify())將顯示更改的鏈接。 要將更改保存到文件:

htmlDoc.close()

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

要保留文檔的原始字符編碼,可以使用soup.original_encoding而不是“utf-8”。 編碼

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM