How to search only the first occurring item? When finding stop searching.

For example:

name = item.cssselect('span.title') 

Looking for spans with class title.

If we know for sure that there is only 1 element in the tree, why should we continue the search after finding the element, because time is wasted on it.

Similar to the find command in Beautiful Soup 4, which only searches for the first matching element

Search can be carried out as xpath, and cssselect.

  • 3
    Is this a practical problem? Have you measured the performance and your profiler says that cssselect () is a bottleneck in your application? Try to compare performance with etree.XPath(f'({xpath_expr})[1]')(item) where xpath_expr = cssselect.HTMLTranslator().css_to_xpath(css_selector) ¶ If the document is large, you can work with it in parts, for example . - jfs

1 answer 1

You can use the pseudo :first-child class :first-child in cssselect.

  • Do not quite understand. How for example for such a line to apply? table_language = html.cssselect ('table.game_language_options') [0] - danilshik
  • Any first table: cssselect('table:first-child') , the first table with the class .game_language_options : cssselect('table.game_language_options:first-child') Examples on w3.org - Georgy R.
  • This is not only the "first matching item" returns. Try: [el.text for el in lxml.cssselect.CSSSelector('div.C:first-child')(doc)] , where doc = lxml.etree.fromstring('<root><div class="C">a<div class="C">b</div></div></root>') - jfs