【问题标题】:Keep children when replacing tag using BeautifulSoup [duplicate]使用 BeautifulSoup 替换标签时保留孩子 [重复]
【发布时间】:2015-08-26 11:17:08
【问题描述】:

我正在尝试替换表单标签而不删除其子标签。例如,我想转换这个:

<form>
    <input type="text"/>
    <input type="text"/>
</form>

到这里:

<p>
    <input type="text"/>
    <input type="text"/>
</p>

但是我得到了:

<p></p>

这就是我现在正在尝试的方式:

from bs4 import BeautifulSoup

content = '<form><input type="text"/><input type="text"/></form>'
soup = BeautifulSoup(content)

old_form = soup.find('form')
new_form = soup.new_tag('p')

old_form.replace_with(new_form)  
print soup

提前感谢您的帮助!

【问题讨论】:

    标签: python beautifulsoup


    【解决方案1】:

    使用.name 属性对我有用:

    from bs4 import BeautifulSoup
    
    content = '<form><input type="text"/><input type="text"/></form>'
    soup = BeautifulSoup(content)
    
    form = soup.find('form')
    form.name = 'p'
    
    print form.prettify()
    <p>
     <input type="text"/>
     <input type="text"/>
    </p>
    

    【讨论】:

    • 这么简单的解决方案,谢谢!
    猜你喜欢
    • 1970-01-01
    • 2016-04-15
    • 2018-09-06
    • 1970-01-01
    • 2014-03-09
    • 1970-01-01
    • 1970-01-01
    • 2020-10-20
    • 2021-08-01
    相关资源
    最近更新 更多