【发布时间】:2021-06-02 10:43:03
【问题描述】:
在 html 文件中搜索一些文本块后,喜欢这个:
s="the Quick brown fox..."
from bs4 import BeautifulSoup
soup = BeautifulSoup(open('file.html'), 'html.parser')
matches = soup.find_all(lambda x: x.text == s)
for match in matches:
print(match.parent)
<div class="container-box"><div class="title-box">label</div><p span="" style="font-:normal">the Quick brown fox...</p></div>
如何在 html 文件中仅替换匹配条目的 label 字符串?例如,对于上面找到的元素,我想将label替换为tomatoes?
<div class="container-box"><div class="title-box">tomatoes</div><p span="" style="font-:normal">the Quick brown fox...</p></div>
到目前为止,我尝试过这个:
在:
matches = soup.find_all(lambda x: x.text == s)
for match in matches:
target = match.parent.find("div", {"class": "title-box"})
print(target.replace_with("tomatoes"))
输出:
<div class="title-box">label</div>
【问题讨论】:
标签: python html beautifulsoup lxml