Path: csiph.com!usenet.pasdenom.info!weretis.net!feeder4.news.weretis.net!newsfeed.fsmpi.rwth-aachen.de!news-1.dfn.de!news.dfn.de!news.informatik.hu-berlin.de!fu-berlin.de!uni-berlin.de!individual.net!not-for-mail From: Neil Cerutti Newsgroups: comp.lang.python Subject: Re: xml.etree.ElementTree if element does not exist? Date: 29 Apr 2013 12:25:34 GMT Organization: Norwich University Lines: 34 Message-ID: References: Mime-Version: 1.0 Content-Type: text/plain; charset=us-ascii Content-Transfer-Encoding: 7bit X-Trace: individual.net /Ig/Rt3ikw6Pw0Q1hptp3wKUC8ApaXNPOX2ufseIdaUrtMBwaE Cancel-Lock: sha1:3yTfiA+QtdBsw6MJ/gNCSYn45p8= User-Agent: slrn/0.9.9p1/mm/ao (Win32) Xref: csiph.com comp.lang.python:44498 On 2013-04-29, Ombongi Moraa Fe wrote: > > Good Afternoon, > > Among other elements values that my script finds is value for sepid > > sepid = content.find(".//{http://www.huawei.com.cn/schema/common/v2_1}sepid > ").text > > > however, if i pass xml data that DOES NOT contain sepid element, i get an > error: > > Traceback (most recent call last): > File "/usr/local/bin/receive.py", line 21, in > sepid = content.find(".//{ > http://www.huawei.com.cn/schema/common/v2_1}sepid").text > AttributeError: 'NoneType' object has no attribute 'text' find returns None when it doesn't find what you asked for. So you can't check the .text attribute right away unless you want an exception thrown. I deal with these annoyances like this: sepelem = content.find(".//{http://www.huawei.com.cn/schema/common/v2_1}sepid") if sepelem is not None: sepid = sepid.text else: sepid = '' The empty string works for my purposes. Your script might need something else. -- Neil Cerutti