如果找不到数据,如何使XPath在Python中返回"None"? [英] How to make XPath return 'None' in Python if no data found?
本文介绍了如果找不到数据,如何使XPath在Python中返回"None"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果子元素没有文本值,则XPath不返回任何内容.在这种情况下,收视率没有数据,所以我想这样说-这个孩子没有或什么都没有,而不仅仅是忽略它.非常感谢您的投入.
XPath returns nothing if a child element has no text value. In this case, rating has no data, so I want it to say so - None or nothing in this child instead of just ignoring it. Your input is much appreciated.
XML:
<?xml version="1.0" encoding="ISO-8859-1"?>
<bookstore>
<book>
<title lang="eng">Harry Potter</title>
<price>29.99</price>
<rating></rating>
</book>
<book>
<title lang="hindi">Learning XML</title>
<price>39.95</price>
<rating></rating>
</book>
</bookstore>
Python:
>>> import lxml.html as lh
>>> bk=open('book.xml','r')
>>> bkout=lh.parse(bk)
>>> bk.close()
>>> bkout.xpath('//book/*/text()')
['Harry Potter', '29.99', 'Learning XML', '39.95']
>>> bkout.xpath('//book/* and not(text())/text()')
True
所需的输出:
['Harry Potter', '29.99', '', 'Learning XML', '39.95', '']
or
['Harry Potter', '29.99', None, 'Learning XML', '39.95', None]
推荐答案
删除"text()":
Remove the "text()":
In [16]: [x.text for x in bk.xpath("//book/*")]
Out[16]: ['Harry Potter', '29.99', None, 'Learning XML', '39.95', None]
这篇关于如果找不到数据,如何使XPath在Python中返回"None"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文