【问题标题】:Look for XML tag value and select the parent which contains the requested tag value查找 XML 标记值并选择包含请求标记值的父级
【发布时间】:2016-01-19 01:53:41
【问题描述】:

我有很多通过 Google Geo API 获得的 XML 文件。我对标签 long_name 的值感兴趣,其中 type 标签包含值 route

我可以用下面的代码选择这个值:

from bs4 import BeautifulSoup as bs

xml_data = '''
<result>
    <formatted_address>Pariser Platz, 10117 Berlin, Deutschland</formatted_address>
    <address_component>
        <long_name>Pariser Platz</long_name>
        <type>route</type>
    </address_component>
    <address_component>
        <long_name>Mitte</long_name>
    <type>sublocality_level_1</type>
    </address_component>
</result>
'''

bsObj = bs(xml_data, 'html.parser')

bsObj.find_all('long_name')[1].string

不幸的是,所需 XML 标记的索引(在本例中为 1)有时会发生变化,因此我不会每次都获得路由标记。所以我在寻找一种策略,首先寻找类型值路由,然后选择上一个兄弟。

【问题讨论】:

    标签: python xml beautifulsoup


    【解决方案1】:

    要选择文本等于route 的第一个type 标记的前一个long_name 兄弟,请使用:

    long_name_tag = bsObj.find('type', text='route').findPreviousSibling('long_name')
    

    或者,要从相关的long_name 标记返回文本字符串,请使用:

    long_name_tag_text = bsObj.find('type', text='route').findPreviousSibling('long_name').text
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-11-19
      • 1970-01-01
      • 2021-01-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-28
      相关资源
      最近更新 更多