I would like to apply a transformation, say uppercase, to all the text nodes inside a given node. I came up with the following code which works fine for my sample input.

Is there something else that should be considered? I felt that the usage of text vs tail in lxml is a bit asymmetric because text needs to be applied to the main node and tail needs to be applied to the child node.

Can someone review this code?

import lxml.html   

def transform(node):
    if node.text:
        node.text = node.text.upper()
    for child in node.getchildren():
        if child.tail:
            child.tail = child.tail.upper()

Here is the test case used:

html = """
      <link href="great.css" rel="stylesheet" type="text/css">
      <title>Best Page Ever</title>
      Body Start
      <div id="1">
         Div 1 Start
         <div id="11">
            Div 11 Start
            Address 1
            Address 2
            Div 11 End
         <div id="12">
            Div 12 Start
            <div id="121">
              Inside Div 121
            Div 12 End
         Div 1 End
      Body End

root = lxml.html.fromstring(html)



Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.