首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >python3汤,替换html元素内容并保存到文件

python3汤,替换html元素内容并保存到文件
EN

Stack Overflow用户
提问于 2018-06-19 06:51:50
回答 1查看 592关注 0票数 1

如何替换文件中html标签的文本内容并将其保存到另一个(某些)文件中?

例如。有一个文件index.html

<!DOCTYPE html>
<html>
    <head>
    </head>
    <body>
        <p itemprop="someprop">SOME BIG TEXT</p>
    </body>
</html>

我需要将"p“标记中的文本”一些大文本“替换为”另一个大文本“。

from bs4 import BeautifulSoup

with open("index.html","r") as file:
 fcontent=file.read()
 sp=BeautifulSoup(fcontent,'lxml')
 t='new_text_for_replacement'

 print(sp.replace(sp.find(itemprop="someprop").text,t))

我做错了什么?

谢谢

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-06-19 07:16:09

在输出文件上使用open()进行写入。

with open('index.html', 'r') as file:
    fcontent = file.read()

sp = BeautifulSoup(fcontent, 'html.parser')

t = 'new_text_for_replacement'

# replace the paragraph using `replace_with` method
sp.find(itemprop='someprop').replace_with(t)

# open another file for writing
with open('output.html', 'w') as fp:
    # write the current soup content
    fp.write(sp.prettify())

如果只想替换段落的内部内容,而不是段落元素本身,则可以设置.string属性。

sp.find(itemprop='someprop').string = t
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50918462

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档