1

I'm building off of the example 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)

As you can see. 1/3/2014 is outside of the tag <FONT COLOR>. I need the <FONT COLOR> tag to be wrapped around 1/3/2014

Keyur Potdar
  • 7,158
  • 6
  • 25
  • 40
jason
  • 3,811
  • 18
  • 92
  • 147

1 Answers1

3

You can use wrap on the contents of the required tag.

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)
Keyur Potdar
  • 7,158
  • 6
  • 25
  • 40