[lxml-dev] how knowing the types return by .xpath
Stefan Behnel
stefan_ml at behnel.de
Wed Feb 4 20:56:40 CET 2009
Hi,
Sergio Monteiro Basto wrote:
> Example:
>
> from lxml import etree
>
> f = open(options.file).read()
>
> hparser = etree.HTMLParser(encoding='utf-8', remove_comments=True)
> etree_document = etree.HTML(f, parser=hparser)
>
> elems=etree_document.xpath(strxpath)
>
> for frags in elems:
> print type (frags)
> (...)
>
> if strxpath is equal //h1/following-sibling::text()
> prints
> <type 'lxml.etree._ElementUnicodeResult'>
>
> if strxpath is equal //div[@class="news"]
> prints
> <type 'lxml.etree._Element'>
>
> How I do a "if" to detected the types ?
It's actually rare that the expected type isn't known in advance, but for
this kind of use case, you can just test the type as usual, i.e. use
isinstance() to check for basestring, float or list.
Stefan
More information about the lxml-dev
mailing list