我试图找出xml在以下xml中是否包含subtypemismatch =“ true”文本。
<boardgames termsofuse="https://boardgamegeek.com/xmlapi/termsofuse">
<boardgame objectid="45987" subtypemismatch="true">
<yearpublished/>
如果我将BeautifulSoup与以下代码一起使用,则可以获取“ true”或“ false”,但是我需要阅读的大多数xml都不包含subtypemismatch文本,这会导致“ KeyError:'subtypemismatch” '“ 发生。如何确定xml是否以该文本开头?
data = response.read()
text = data.decode('utf-8')
soup = BeautifulSoup(text,'xml')
if soup.find('boardgame')['subtypemismatch'] != 'true':
do something....
答案 0 :(得分:1)
为避免获取KeyError
,请使用get
而不是方括号来访问属性:
if soup.find('boardgame').get('subtypemismatch') != 'true':
如果元素不具有属性,则get
返回None
。您还可以为其设置默认值:
if soup.find('boardgame').get('subtypemismatch', 'false') != 'true':
您还可以使用has_attr
来测试属性的存在而无需获取其值:
soup = BeautifulSoup(text, 'xml')
for boardgame in soup.find_all('boardgame'):
if boardgame.has_attr('subtypemismatch'):
print('has attribute')
else:
print('does not have attribute')