代码之家  ›  专栏  ›  技术社区  ›  jason

使用已有值的beautifulsoup将标记插入html

  •  1
  • jason  · 技术社区  · 7 年前

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

    import pandas
    from bs4 import BeautifulSoup
    
    a = [['1/2/2014', 'a', '6', 'z1'],
         ['1/2/2014', 'a', '3', 'z1'],
         ['1/3/2014', 'c', '1', 'x3'],
         ]
    df = pandas.DataFrame.from_records(a[1:], columns=a[0])
    soup = BeautifulSoup(df.to_html(header=False), 'lxml')
    
    original_tag = soup.find_all('td')[4]
    new_tag = soup.new_tag('FONT', COLOR='white')
    original_tag.append(new_tag)
    print(soup)
    

    如你所见。 1/3/2014 <FONT COLOR> . 我需要 < 要包裹的标签 1/3/2014

    1 回复  |  直到 7 年前
        1
  •  3
  •   Keyur Potdar    7 年前

    wrap

    import pandas
    from bs4 import BeautifulSoup
    
    a = [['1/2/2014', 'a', '6', 'z1'],
         ['1/2/2014', 'a', '3', 'z1'],
         ['1/3/2014', 'c', '1', 'x3']]
    df = pandas.DataFrame.from_records(a[1:], columns=a[0])
    soup = BeautifulSoup(df.to_html(header=False), 'lxml')
    
    original_tag = soup.find_all('td')[4]
    new_tag = soup.new_tag('FONT', COLOR='white')
    original_tag.contents[0].wrap(new_tag)
    print(soup)