Getting exactly one element or raising an exception with lxml xpath

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

If I have XPath that I expect to return exactly one element, then what's the best way:

  • Make sure one item is returned or throw an exception, and:
  • Get this item (as opposed to a single-item list)?

I am really looking for an analogue to the SQLAlchemy one () function.

+4
source share
1 answer
try: (element,) = tree.xpath('//xpath/selector') except ValueError: raise InvalidSelector() # happened because the list was either empty or contained multiple elements 
+16
source

Source: https://habr.com/ru/post/1436523/


All Articles