Skip to content

Instantly share code, notes, and snippets.

@walkerdb
Created October 2, 2015 19:27
Show Gist options
  • Select an option

  • Save walkerdb/3ce4c343a66b473d6926 to your computer and use it in GitHub Desktop.

Select an option

Save walkerdb/3ce4c343a66b473d6926 to your computer and use it in GitHub Desktop.
# 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