How to insert tag before a string in html using python -
i finding text in html document , want add span tag holds information each text below
def recursivechildren(x): if "childgenerator" in dir(x): child in x.childgenerator(): recursivechildren(child) else: if not x.isspace(): content = x.string new_tag = soup.new_tag("span") content.insert_before(new_tag) if __name__ == "__main__": open("path html",'r') file: soup = beautifulsoup(file) child in soup.body.childgenerator(): recursivechildren(child)
i getting error string object has no attribute insert before. how can insert tag before string. tried getting parent tag of string , add add span tag before parent tag contents creates problem if there nested tags want span tag before each , every independent string. possible? below in python insert span tag before # content text
adding span before specific string jquery
example html:
<p class=msonormal >this first string <b> second string </b> , </span><span style='font-family:"times new roman"><o:p></o:p></span></p>
i want output like
<p class=msonormal >**<span>**this first string</span> <b>**<span>** second string </span></b>**<span>** , </span><span style='font-family:"times new roman"><o:p></o:p></span></p>
content = x.string
content.insert_before(new_tag)
problem.
if not x.isspace(): new_tag = soup.new_tag("span") x.insert_before(new_tag)
soup.body.childgenerator()
returns list of bs4.element
. these able perform complex operations, insert trying do.
this function recursivechildren
got argument x
. x
able insert_before
.
but when doing content = x.string
storing within content
simple html string (type of str
in python). string not support insert_before
- have on x
.
btw, should give @ pep8 - recursivechildren
better named recursive_children
, x
bad variable name, should name element
or that.
Comments
Post a Comment