【问题标题】:Inserting tag into html with beautifulsoup with values already existing使用已经存在的值的 beautifulsoup 将标签插入到 html 中
【发布时间】:2019-07-31 10:12:15
【问题描述】:

我正在构建示例 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> 之外。我需要将<FONT COLOR> 标签包裹在1/3/2014 周围

【问题讨论】:

    标签: python beautifulsoup tags


    【解决方案1】:

    您可以在所需标签的内容上使用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)

    【讨论】:

      猜你喜欢
      • 2023-03-24
      • 1970-01-01
      • 2015-07-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-17
      • 2020-07-27
      • 1970-01-01
      相关资源
      最近更新 更多