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

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

问题描述

Python的小白在这里...

我有下面的脚本,该脚本修改的HREFs一个HTML文件(在未来这将是HTML文件的目录列表)。使用beautifulSoup我设法访问变量值并修改它,因为我想,但我不知道如何保存回文件所做的更改。任何帮助将大大AP preciated。

 导入OS
进口重
从BS4进口BeautifulSoup
HTMLDOC =开放('adding_computer_c.html,R +)
汤= BeautifulSoup(HTMLDOC)置换= [('_',' - '),('../tasks/',prefixUrl),('../concepts/',prefixUrl)在soup.findAll链路('一个',ATTRS = {'的href':re.compile(../)}):
    NEWLINK = STR(链接)    对于K,V在更换:        NEWLINK = newlink.replace(K,V)    extrachars = NEWLINK [newlink.find(。):newlink.find(>中)]
    NEWLINK = newlink.replace(extrachars,'')
    链接= NEWLINK
    打印(链接)
    ##我如何保存我修改回HTML文件的链接?打印(汤)##打印原始的HTML树htmlDoc.close()


解决方案

  = NEWLINK链接['href属性]
#..使替代
链接['的href'] =#NEWLINK店里回来

现在打印(汤。prettify())将显示更改后的链接。要更改保存到一个文件:

  htmlDoc.close()HTML =汤。prettify(UTF-8)
开放(output.html,世行)的文件中:
    file.write(HTML)

要在文档的preserve原始字符编码,你可以使用 soup.original_encoding ,而不是UTF-8。请参见的编码

Python noob here...

I have the script below, which modifies the hrefs for a 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 it as I want but I don't know how to save back the changes made to the file. Any help will be greatly appreciated.

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

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)

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天全站免登陆