Python lxml cannot get all text

Viewed 69

I am using Python lxml library for parsing HTML. I have got leaf point such as <a> and want to get its parent’s text. I tried doing it in two ways:

  1. .xpath('::parent*'),
  2. .getparent().text.
from lxml.etree import HTML
text = '<p>FIRST PART<a href="THE LINK" target="_blank">LINK TEXT</a>SECOND PART</p>'

parsed = HTML(text)
parsed.xpath('//a')[0].getparent().text
parsed.xpath('//a/parent::*')[0].text

I got FIRST PART using either approach, but how can I obtain the SECOND PART?

1 Answers

You can use .itertext() method of an Element:

from lxml.etree import HTML

text = '<p>FIRST PART<a href="THE LINK" target="_blank">LINK TEXT</a>SECOND PART</p>'
parsed = HTML(text)

parent = parsed.xpath('//a/parent::*')[0]
text = list(parent.itertext())
print(text[0])
print(text[-1])

Prints:

FIRST PART
SECOND PART
Related