NeelDeveloper
NeelDeveloper

Reputation: 137

Inserting tag within a tag using BeautifulSoup

I have the following HTML structure:

<BODY><tag1></tag1><tag2></tag2></BODY>

I need to insert a table just prior to </BODY> using BeautifulSoup.

What I have till now is:

re.sub(r'\s/BODY\s', '<Table>Test<Table></BODY>', BeautifulSoup(report, "lxml"))

The error I get is:

Traceback (most recent call last):
  File "<pyshell#13>", line 1, in <module>
    execfile("C:\Users\My_PC\Desktop\Report.py")
  File "C:\Users\My_PC\Desktop\Report.py", line 10, in <module>
    re.sub(r'\s/BODY\s', '<Table>Test<Table></BODY>', BeautifulSoup(report, "lxml"))
  File "C:\Python27\lib\re.py", line 155, in sub
    return _compile(pattern, flags).sub(repl, string, count)
TypeError: expected string or buffer

Any help would be appreciated.

Upvotes: 1

Views: 752

Answers (1)

Padraic Cunningham
Padraic Cunningham

Reputation: 180391

You don't need a regex, you can just append the table to the body:

In [45]: soup = BeautifulSoup("<BODY><tag1></tag1><tag2></tag2></BODY>", "html.parser")

In [46]: soup.body.append(BeautifulSoup("<table>Test</table>","html.parser"))

In [47]: soup
Out[47]: <body><tag1></tag1><tag2></tag2><table>Test</table></body>

Upvotes: 1

Related Questions