python - 根据多个标签文本查找父标签 - BeautifulSoup

标签 python xml beautifulsoup

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

考虑我在文件中有部分 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。

所以我需要同时传递类型和用法,以便我可以获得客户端名称。

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

最佳答案

有点像

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

关于python - 根据多个标签文本查找父标签 - BeautifulSoup,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41217741/

相关文章:

python - 尝试使用 pysftp 获取文件时没有获取任何内容

python - Ansible - "NameError: name ' urllib 2' is not defined"

java - 是否有我可以引用的可能的 IllegalAnnotationExceptions 列表?

java - 用Java修改并输出成XML文件

python - 如何在 python 中异步处理 xml?

javascript - Python urllib2.unquote() 与 Javascript unescape()

python - Pandas 多索引数据帧 : creating new index or appending to existing index

python - 如何使用 BeautifulSoup 从表中获取第一个和第三个 td?

python - "unit tests have failed"for beautifulsoup

javascript - 抓取需要您向下滚动的网站