Add parent tags with beautiful soup

后端 未结 1 2066
一向
一向 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("Some text")
    wrap(soup.a, soup.new_tag("b"))
    print soup.body
    # Some text
    

    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)
提交回复
热议问题