getparent() fails with "AttributeError: 'list' object has no attribute 'getparent' "
Hello, I'd like to find and replace an element in an HTML file. I can't figure out why getparent() doesn't work as expected: ============== import lxml.html from lxml.html import builder as E import lxml.etree as et import lxml.etree as et parser = et.HTMLParser(remove_blank_text=True,recover=True) with open("template.tmpl") as tempfile: template_tree = et.parse(tempfile, parser=parser) template_root = template_tree.getroot() #BAD FOO = template_root.find('.//FOO') FOO = template_root.xpath('//FOO') if len(FOO): print("FOO:",FOO) #AttributeError: 'list' object has no attribute 'getparent' parent = FOO.getparent() parent.insert(parent.index(FOO)+1,ET.XML("<bar/>")) #Remove FOO, no longer needed else: print("Not FOO") ============== What am I doing wrong? Thank you.
Here's template.tmpl: ======= … <body> <div class="entrycontent"> <HERE/> =======
Through trial and error, it looks like xpath() returns an array, even if only one element is found in the tree. This works: HERE = template_tree.xpath('//here') if len(HERE): print("HERE:",HERE) parent = HERE[0].getparent() html_tree = lxml.html.fragment_fromstring("<div>blah</div>", parser=lxml.html.HTMLParser()) parent.insert(parent.index(HERE[0]),html_tree) parent.remove(HERE[0]) print(et.dump(template_root)) else: print("Not HERE")
participants (1)
-
codecomplete@free.fr