6

The xpath() function in lxml normally returns a list of elements.

If I have an XPath which I expect to return exactly one element, what's the nicest way to:

  • Check that one element is returned or else raise an exception, and:
  • Get that element (as opposed to a one-element list)?

I'm really looking for the analogue of SQLAlchemy's one() function.

mskel
  • 842
  • 9
  • 16

1 Answers1

19
try:
    (element,) = tree.xpath('//xpath/selector')
except ValueError:
    raise InvalidSelector()
    # happened because the list was either empty or contained multiple elements
andrean
  • 6,717
  • 2
  • 36
  • 43