How can I insert a new tag into a BeautifulSoup object?

前端 未结 3 2065
小鲜肉
小鲜肉 2020-11-30 08:39

Trying to get my head around html construction with BS.

I\'m trying to insert a new tag:

self.new_soup.body.insert(3, \"\"\"
相关标签:
3条回答
  • 2020-11-30 08:57

    See the documentation on how to append a tag:

    soup = BeautifulSoup("<b></b>")
    original_tag = soup.b
    
    new_tag = soup.new_tag("a", href="http://www.example.com")
    original_tag.append(new_tag)
    original_tag
    # <b><a href="http://www.example.com"></a></b>
    
    new_tag.string = "Link text."
    original_tag
    # <b><a href="http://www.example.com">Link text.</a></b>
    
    0 讨论(0)
  • 2020-11-30 09:04

    Use the factory method to create new elements:

    new_tag = self.new_soup.new_tag('div', id='file_history')
    

    and insert it:

    self.new_soup.body.insert(3, new_tag)
    
    0 讨论(0)
  • 2020-11-30 09:21

    Other answers are straight off from the documentation. Here is the shortcut:

    from bs4 import BeautifulSoup
    
    temp_soup = BeautifulSoup('<div id="file_history"></div>')
    # BeautifulSoup automatically add <html> and <body> tags
    # There is only one 'div' tag, so it's the only member in the 'contents' list
    div_tag = temp_soup.html.body.contents[0]
    # Or more simply
    div_tag = temp_soup.html.body.div
    your_new_soup.body.insert(3, div_tag)
    
    0 讨论(0)
提交回复
热议问题