如何替换文件中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))
我做错了什么?
谢谢
发布于 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
https://stackoverflow.com/questions/50918462
复制相似问题