Created
October 2, 2015 19:27
-
-
Save walkerdb/3ce4c343a66b473d6926 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # create a text representation of the element | |
| # etree.tostring() spits out all text, including tags and subtags | |
| text = etree.tostring(element_with_complex_text) | |
| # do the manipulation | |
| text = text.replace("Prince", "Artist formerly known as Prince") | |
| # transform that text back into an lxml element | |
| new_element = etree.fromstring(text) | |
| # get the index of the old element from its parent | |
| parent = element_with_complex_text.getparent() | |
| index = parent.index(element_with_complex_text) | |
| # remove the old element | |
| parent.remove(element_with_complex_text) | |
| # insert the new one | |
| parent.insert(index, new_element) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment