问题
I need to replace a matching pair of HTML tags by another tag. Probably BeautifulSoup (4) would be suitable for the task, but I've never used it before and haven't found a suitable example anywhere, can someone give me a hint?
For example, this HTML code:
<font color="red">this text is red</font>
Should be changed to this:
<span style="color: red;">this text is red</span>
The beginning and ending HTML tags may not be in the same line.
回答1:
Use replace_with() to replace elements. Adapting the documentation example to your example gives:
>>> from bs4 import BeautifulSoup
>>> markup = '<font color="red">this text is red</font>'
>>> soup = BeautifulSoup(markup)
>>> soup.font
<font color="red">this text is red</font>
>>> new_tag = soup.new_tag('span')
>>> new_tag['style'] = 'color: ' + soup.font['color']
>>> new_tag.string = soup.font.string
>>> soup.font.replace_with(new_tag)
<font color="red">this text is red</font>
>>> soup
<span style="color: red">this text is red</span>
来源:https://stackoverflow.com/questions/15545594/using-python-beautifulsoup-to-replace-html-tag-pair-with-a-different-one