将 <strong> 标签替换为 h2 标签

Sim*_*ely 2 html python beautifulsoup html-parsing python-3.x

我正在尝试编写一些 BeautifulSoup 代码,它将采用标签包围的每一段文本并将标签更改为标签 - 但是,只有当它只是一行没有其他书面/输出文本时。

这可能吗?

前

对此

后

但这将保持不变:

不变

我知道以下内容将有助于改变所有强者。我怎样才能只获取重要的?

import BeautifulSoup

if __name__ == "__main__":
    data = """
<html>
<h2 class='someclass'>some title</h2>
<ul>
   <li>Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</li>
   <li>Aliquam tincidunt mauris eu risus.</li>
   <li>Vestibulum auctor dapibus neque.</li>
</ul>
</html>

    """
    soup = BeautifulSoup.BeautifulSoup(data)
    h2 = soup.find('strong')
    h2.name = 'h1'
    print soup
Run Code Online (Sandbox Code Playgroud)

ale*_*cxe 6

你都可以找到strong元素并检查 的长度.parent

from bs4 import BeautifulSoup

data = """
<html>
<p><strong>Like this</strong></p>
<p>Hello, <strong>world</strong>
</html>
"""

soup = BeautifulSoup(data)
for strong in soup.find_all('strong'):
    if len(strong.parent) == 1:
        strong.name = 'h1'
print soup
Run Code Online (Sandbox Code Playgroud)

打印(看到第一个strong标签被替换,第二个标签未被替换):

<html>
<body>
    <p><h1>Like this</h1></p>
    <p>Hello, <strong>world</strong></p>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

或者,以更简洁的形式:

for strong in soup.find_all('strong', lambda x: x and len(x.parent) == 1):
    strong.name = 'h1'
Run Code Online (Sandbox Code Playgroud)

附带说明一下,您正在使用的BeautifulSoup3不再维护;考虑升级到BeautifulSoup4

pip install beautifulsoup4
Run Code Online (Sandbox Code Playgroud)