python - 如何用漂亮的汤替换 HTML 元素的值?
问题描述
在 html 文件中搜索一些文本 blob 后,喜欢这个:
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>
解决方案
尝试这个:
for match in matches:
#target = match.parent.find('div')
#EDIT
target = match.parent.select_one('div.title-box')
target.replace_with("tomatoes")
soup
输出:
<html><body><div class="container-box">tomatoes<p span="" style="font-:normal">the Quick brown fox...</p></div>
</body></html>
推荐阅读
- java - 哪种方法更适合将微服务应用程序迁移到云端?Kubernetes、AWS Lambda等如何选择?
- github - 在 Github 中查看/恢复待处理的代码审查
- vhdl - 在 VHDL 中乘以浮点和整数文字
- excel - 如果满足条件,用于复制和粘贴特定单元格的 VBA 代码
- class - 模板类中的模板函数“在此上下文中是私有的”错误
- javascript - 如何在 TypeScript 中键入重载箭头函数的参数?
- flutter - 如何生成随机 CircleAvatars 占位符
- python - 更新 Django Rest Api 中的列会导致“列不能为空”错误
- sql - 按多列问题分组
- javascript - 如何使用 JSON.stringify 输出每个数组项都是新行的 javascript 数组