2014-07-09 92 views
2

此代碼:LXML元布爾檢查

from lxml.html import fromstring, tostring 

s = '<span class="left">Whatever</span>' 
e = fromstring(s) 
print(tostring(e)) 
print(bool(e)) 

輸出:

<span class="left">Whatever</span> 
False 

爲什麼?如何布爾檢查在這個類中工作?請指出我的相關文件或代碼。

PS
進出口使用lxml 3.3.5

+0

如果你想測試一些不是空的:'not not「」'is False while'not not「something」'是True – daouzli

回答

0

這是我與你的代碼...

>>> print(bool(e)) 
__main__:1: FutureWarning: The behavior of this method will change in future ve 
sions. Use specific 'len(elem)' or 'elem is not None' test instead. 
False 
>>> e 
<Element span at 0x2db85a0> 
>>> 

似乎很清楚,他們超載__bool__方法,告訴你你應該如何實際檢查它...

1

XML和HTML不會乾淨地映射到本地python數據結構。沒有明確的方法來決定元素對象是否應該等同於True或False。

如果您想知道您是否未能獲取元素,請與None比較。例如: -

element is None 

如果你想知道你的元素是否擁有子節點,使用len。例如:

len(element) > 0