Beautiful Soup 4: How to replace a tag with text and another tag?

前端 未结 1 447
陌清茗
陌清茗 2021-02-14 07:10

I want to replace a tag with another tag and put the contents of the old tag before the new one. For example:

I want to change this:




        
1条回答
  •  生来不讨喜
    2021-02-14 07:47

    The idea is to find every span tag with id attribute (span[id] CSS Selector), use insert_after() to insert a sup tag after it and unwrap() to replace the tag with it's contents:

    from bs4 import BeautifulSoup
    
    data = """
    
    
    

    This is the first paragraph

    This is the second paragraph

    """ soup = BeautifulSoup(data) for span in soup.select('span[id]'): # insert sup tag after the span sup = soup.new_tag('sup') sup.string = span['id'] span.insert_after(sup) # replace the span tag with it's contents span.unwrap() print soup

    Prints:

    
    
    

    This is the first1 paragraph

    This is the second2 paragraph

    0 讨论(0)
提交回复
热议问题