Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting exactly one element or raising exception with lxml xpath

Tags:

python

xpath

lxml

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.

like image 641
mskel Avatar asked Sep 27 '12 06:09

mskel


1 Answers

try:
    (element,) = tree.xpath('//xpath/selector')
except ValueError:
    raise InvalidSelector()
    # happened because the list was either empty or contained multiple elements
like image 158
andrean Avatar answered Nov 12 '22 05:11

andrean