【问题标题】:Replace <strong> tag with h2 tag将 <strong> 标签替换为 h2 标签
【发布时间】:2015-03-26 10:15:51
【问题描述】:

我正在尝试编写一些 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

【问题讨论】:

    标签: python html python-3.x beautifulsoup html-parsing


    【解决方案1】:

    您可以找到所有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
    

    打印(见第一个strong标签被替换,第二个没有):

    <html>
    <body>
        <p><h1>Like this</h1></p>
        <p>Hello, <strong>world</strong></p>
    </body>
    </html>
    

    或者,更简洁的形式:

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

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

    pip install beautifulsoup4
    

    【讨论】:

    • 虽然 OP 需要 bs4
    【解决方案2】:

    erm... 这可能效率不高,但写起来肯定更简单:

    data = data.replace('<p><strong>', '<p><h2>')
    data = data.replace('</strong></p>', '</h2></p>')
    

    还是我误解了有关 str.replace() 的一些基本内容?

    虽然这不是很复杂,但如果 html 是一致的,就可以完成这项工作

    编辑:使用正则表达式的更复杂的解决方案:

    import re
    
    data = re.sub(r'<[Pp]>[\s]*<[Ss][Tt][Rr][Oo][Nn][Gg]>', '<p><h2>', data)
    data = re.sub(r'</[Ss][Tt][Rr][Oo][Nn][Gg]>[\s]*</[Pp]>', '</h2></p>', data)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-03-09
      • 2013-06-02
      • 1970-01-01
      • 1970-01-01
      • 2013-01-17
      • 2011-03-23
      • 1970-01-01
      • 2020-10-19
      相关资源
      最近更新 更多