[lxml-dev] how knowing the types return by .xpath
Dirk Rothe
d.rothe at semantics.de
Wed Feb 4 21:15:58 CET 2009
On Wed, 04 Feb 2009 20:56:40 +0100, Stefan Behnel <stefan_ml at behnel.de>
wrote:
> 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.
..or scalar bools.
I was quite surprised to see that the xpath function can return other
types than lists:
>>> tree.xpath('count(/) = 1')
True
More information about the lxml-dev
mailing list