【问题标题】:Find parent Tag based on multiple tag text - BeautifulSoup根据多个标签文本查找父标签 - BeautifulSoup
【发布时间】:2017-05-04 05:14:47
【问题描述】:

根据多标签文本查找父标签

考虑我在文件中有部分 xml 如下:

<Client name="Jack">
        <Type>premium</Type>
        <Usage>unlimited</Usage>
        <Payment>online</Payment>
</Client>

<Client name="Jill">
        <Type>demo</Type>
        <Usage>limited</Usage>
        <Payment>online</Payment>
</Client>

<Client name="Ross">
        <Type>premium</Type>
        <Usage>unlimited</Usage>
        <Payment>online</Payment>
</Client>

我正在使用 BeautifulSoup 来解析值。

这里我需要根据标签获取客户端名称,根据标签的文本,我需要获取客户端名称。(来自父标签)。

我的功能如下:

def get_client_for_usage(self, usage):
    """
    To get the client name for specified usage
    """
    usage_items = self.parser.findAll("client")
    client_for_usage = []
    for usages in usage_items:
        try:
            client_set = usages.find("usage", text=usage).findParent("client")
            client_attr = dict(client_set.attrs)
            client_name = client_attr[u'name']
            client_for_usage.append(client_name)

        except AttributeError:
            continue
    return client_for_usage

现在我需要获取客户端名称,但基于两件事,即基于 Usage 和 Type。

所以我需要同时传递类型和用法,这样我才能得到客户端名称。

有人帮我做同样的事情。如果问题不清楚,请告诉我,以便我可以根据需要进行编辑。

【问题讨论】:

    标签: python xml beautifulsoup


    【解决方案1】:
    html = '''<Client name="Jack">
            <Type>premium</Type>
            <Usage>unlimited</Usage>
            <Payment>online</Payment>
    </Client>
    
    <Client name="Jill">
            <Type>demo</Type>
            <Usage>limited</Usage>
            <Payment>online</Payment>
    </Client>
    
    <Client name="Ross">
            <Type>premium</Type>
            <Usage>unlimited</Usage>
            <Payment>online</Payment>
    </Client>'''
    
    
    import bs4 
    import collections
    
    soup = bs4.BeautifulSoup(html, 'lxml')
    d = collections.defaultdict(list)
    for client in soup('client'):
        type_, usage, payment = client.stripped_strings
        d[(type_, usage)].append(client['name'])
    

    出来:

    defaultdict(list,
                {('demo', 'limited'): ['Jill'],
                 ('premium', 'unlimited'): ['Jack', 'Ross']})
    

    使用typeusage作为键,客户端name作为值来构造一个dict,而不是你可以通过访问key得到name

    【讨论】:

      【解决方案2】:

      类似

      def get_client_for_usage(self, usage, tpe):
          """
          To get the client name for specified usage
          """
          usage_items = self.parser.findAll("client")
          client_for_usage = []
          for usages in usage_items:
              try:
                  client_set = usages.find("usage", text=usage).findParent("client")
                  typ_node = usages.find("type", text=tpe).findParent("client")
                  if client_set == typ_node:
                      client_for_usage.append(client_set['name'])
              except AttributeError:
                  continue
          return client_for_usage
      

      【讨论】:

      • @sathis 如果有助于解决问题,请确保接受答案。谢谢。
      猜你喜欢
      • 2016-01-10
      • 1970-01-01
      • 2020-10-24
      • 1970-01-01
      • 2012-11-04
      • 2013-01-11
      • 2018-10-11
      • 2019-10-08
      • 2020-12-04
      相关资源
      最近更新 更多