[Python] How to get first element from lxml using xpath

Discussão em 'Python' iniciado por Stack, Junho 6, 2025.

  1. Stack

    Stack Membro Participativo

    Minimal example:

    In [1]: from lxml import etree

    In [2]: etree.fromstring('<who>syslogd</who>').xpath('/who/text()')

    Out[2]: ['syslogd']


    currently I'm using helper function:

    def safe_xpath_one(tree: Element, xpath: str) -> Union[Element, None]:
    res = tree.xpath(xpath)
    if res:
    return res[0]


    Here I then need to check first element from result which is additional. Is there direct way of specifying that I want the first and only first element?

    P.S.: I think I got too much used to bs4's soup.select_one

    Continue reading...

Compartilhe esta Página