如何使用Python确定XML标记、属性是否存在?

2024-06-28 19:00:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图找出xml是否包含以下xml中的subsmatch=“true”文本。在

<boardgames termsofuse="https://boardgamegeek.com/xmlapi/termsofuse">
    <boardgame objectid="45987" subtypemismatch="true">
        <yearpublished/>

如果我在下面的代码中使用beauthoulsoup,我可以得到一个“true”或“false”,但是我需要读入的大多数xml都不包含subsmatchmatch文本,这会导致出现“KeyError:'submitsmatch'”。如何确定xml是否以该文本开头?在

^{pr2}$

Tags: 代码https文本comtruexmlobjectidboardgamegeek
1条回答
网友
1楼 · 发布于 2024-06-28 19:00:18

若要避免获取KeyError,请使用get而不是方括号来访问该属性:

if soup.find('boardgame').get('subtypemismatch') != 'true':

如果元素没有属性,get返回None。也可以给它一个默认值:

^{pr2}$

您还可以使用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')

相关问题 更多 >