【问题标题】:How to replace an HTML element's value with beautiful soup?如何用漂亮的汤替换 HTML 元素的值?
【发布时间】: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


    【解决方案1】:

    试试这个:

    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>
    

    【讨论】:

    • 感谢您的帮助,问题是我有几个嵌套的 div。如果我尝试这个解决方案,我将替换其他我不能碰的东西
    • 我试过这个:match.parent.find("div", {"class": "title-box"}).replace_with("tomatoes")
    • @aywoki 我只能处理您在问题中发布的内容。我不知道“真实”的 html 是什么样子的......
    • 问题是它是一个大文件,我只对匹配该字符串的部分感兴趣
    • @aywoki 查看问题中的 EDIT 行并检查您的实际 html。
    猜你喜欢
    • 2014-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多