【问题标题】:How to extract text from xml error message python如何从xml错误消息python中提取文本
【发布时间】:2019-07-14 21:14:50
【问题描述】:

我想确定一个 beautifulsoup 请求的返回是否像这样。

Out[32]: 
<?xml version="1.0" encoding="utf-8"?>
<boardgames termsofuse="https://boardgamegeek.com/xmlapi/termsofuse">
<boardgame>
<error message="Item not found"/>
</boardgame>
</boardgames>

我可以使用以下方法提取上一个输出的中心:

soup.find_all('boardgame')[0], which produces the following:

Out[24]: 
<boardgame>
<error message="Item not found"/>
</boardgame>

我觉得这应该很容易,并且我尝试了以下操作,但我仍然无法确定“错误消息 =“未找到项目”是否在那里。我在这里缺少什么?

soup.findAll('boardgame')[0].getText()
Out[26]: '\n\n'

【问题讨论】:

    标签: python xml beautifulsoup


    【解决方案1】:

    使用属性message获取值。如果先找到error标签再使用属性message

    from bs4 import BeautifulSoup
    
    data='''<?xml version="1.0" encoding="utf-8"?>
    <boardgames termsofuse="https://boardgamegeek.com/xmlapi/termsofuse">
    <boardgame>
    <error message="Item not found"/>
    </boardgame>
    </boardgames>'''
    
    soup=BeautifulSoup(data,'html.parser')
    message=soup.find('boardgame').find('error')['message']
    print(message)
    

    输出:

    找不到项目


    或者你可以使用css选择器

    from bs4 import BeautifulSoup
    
    data='''<?xml version="1.0" encoding="utf-8"?>
    <boardgames termsofuse="https://boardgamegeek.com/xmlapi/termsofuse">
    <boardgame>
    <error message="Item not found"/>
    </boardgame>
    </boardgames>'''
    
    soup=BeautifulSoup(data,'html.parser')
    
    message=soup.select_one('boardgame error')['message']
    print(message)
    

    输出:

    找不到项目

    【讨论】:

      猜你喜欢
      • 2020-03-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-14
      • 2019-02-22
      • 1970-01-01
      相关资源
      最近更新 更多