简体   繁体   English

lxml元素布尔检查

[英]lxml Element boolean check

This code: 这段代码:

from lxml.html import fromstring, tostring

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

outputs: 输出:

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

Why? 为什么? How boolean check working in this class? 布尔检查如何在这个类中工作? Point me on relevant documentation or code please. 请指出相关文档或代码。

ps PS
Im using lxml 3.3.5 我正在使用lxml 3.3.5

The relevant place in the Python documentation: https://docs.python.org/2/library/stdtypes.html#truth-value-testing Python文档中的相关位置: https//docs.python.org/2/library/stdtypes.html#truth-value-testing

The ”truthiness” of an object is determined by either the __nonzero__() method or if that does not exist the result of the __len__() method. 对象的“真实性”由__nonzero__()方法确定,或者如果不存在__len__()方法的结果。 As your element has no child elements, ie its length is 0, it is considered False as a truth value. 当你的元素没有子元素,即它的长度为0,它被认为是False的真值。

XML and HTML don't map cleanly to native python data structures. XML和HTML不能完全映射到本机python数据结构。 There is no unambiguous method to decide whether an element object should equate to True or False. 没有明确的方法来确定元素对象是否应该等于True或False。

If you want to know if you've failed to acquire an element, compare with None . 如果您想知道您是否未能获得元素,请与None进行比较。 Eg: 例如:

element is None

If you want to know whether your element has any child nodes, use len . 如果您想知道您的元素是否有任何子节点,请使用len Eg: 例如:

len(element) > 0

this is what I get with your code ... 这就是我用你的代码得到的......

>>> 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>
>>>

seems pretty clear that they overload the __bool__ method and tell you how you should actually check it ... 似乎很清楚,他们重载__bool__方法并告诉你应该如何实际检查它...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM