【问题标题】:How to add new value to a class with lxml [closed]如何使用 lxml 向类添加新值 [关闭]
【发布时间】:2021-09-15 13:11:56
【问题描述】:

不确定它是否可能 tbh.. 我想做的只是动态编辑文本。

HTML:

 <aside class="banner">
            Place <span class=red>open</span></a>
        </aside>

蟒蛇:

reds = root.find_class("red")
for element in reds:
    *not sure what goes here*

我已经有了可用于远程编辑文本的代码

【问题讨论】:

    标签: python lxml


    【解决方案1】:

    我知道你问的是lxml,但对于 html 文件来说,bs4 是一个很好的选择。

    使用 bs4/BeautifulSoup 看起来像这样:

    for element in soup.find_all("span", { "class": "red"}):
        element.string = NEW_VALUE
    
    with open("out.html", "w") as out_file:
        out_file.write(str(soup))
    

    https://github.com/poleszcz/stack-misc/blob/main/69193852-bs4-edit-content/edit.py

    【讨论】:

    • 我从来不知道这个,谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-07
    • 1970-01-01
    • 2014-04-16
    相关资源
    最近更新 更多