问题
This question already has answers here:
Closed 6 years ago.Possible Duplicate:
How to find/replace text in html while preserving html tags/structure
I want to search and replace through HTML text. I don't want to fiddle with the tags or their attributes, just the HTML text. How should I do that in Python?
回答1:
import lxml.etree as et
html=\
"""
Hello HTMLHello 1
Hello 2
Hello 3
Hello 4
"""
doc = et.fromstring(html)
for i in doc.xpath('.//p[contains(.,"Hello") and not(contains(.,"4"))]'):
i.text='replaced'
print et.tostring(doc,pretty_print=True)
OUT:
Hello HTMLreplaced
replaced
replaced
Hello 4
回答2:
You can try with Re module. Or just use replace function.
But Search and replace is very inefficient processing, if you need to replace on multiple keywords. You should better parse the structure via beautifulSoup or lxml, get the objects, and do some operations on the objects.
来源:https://stackoverflow.com/questions/14134843/search-and-replace-html-text-not-tags