简体   繁体   中英

check whether an element have attribute or not python3

I am using python3.4 and parsing an xml file by etree. some of the node have attribute "meaning" and some of them have attribute "role" and some have both. these nodes may have other attributes but not important to me. I need to extract these attributes (meaning and role) if they are exist. if it is there I used:

role = XMTok.attrib["role"]

but if the node dose not have attribute "role" then it give me this error:

KeyError: 'role'

is there a way to check first if the node have attribute "role" or not, if yes then extract it and if no then continue?

attrib is a standard dictionary, so you can use the in membership operator to test:

if 'role' in XMTok.attrib:

or you can use dict.get() and have a default returned if the key is missing ( None by default, or you can specify something else):

role = XMTok.attrib.get('role', 'No role set')

Use __dict__ to check the attribute. so XMTok.attrib._dict__ will help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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