Add parent tags with beautiful soup

后端 未结 1 2065
一向
一向 2021-01-22 14:49

I have many pages of HTML with various sections containing these code snippets:

Reference:

相关标签:
1条回答
  • 2021-01-22 15:12

    How about this:

    def wrap(to_wrap, wrap_in):
        contents = to_wrap.replace_with(wrap_in)
        wrap_in.append(contents)
    

    Simple example:

    from bs4 import BeautifulSoup
    soup = BeautifulSoup("<body><a>Some text</a></body>")
    wrap(soup.a, soup.new_tag("b"))
    print soup.body
    # <body><b><a>Some text</a></b></body>
    

    Example with your document:

    for footnote in soup.find_all("div", "footnote"):
        new_tag = soup.new_tag("div")
        new_tag['class'] = 'footnote-out'
        wrap(footnote, new_tag)
    
    0 讨论(0)
提交回复
热议问题