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

时间:2018-10-07 02:57:01

标签: python xml beautifulsoup

我试图找出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....

1 个答案:

答案 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')
相关问题