根据多个标签文本查找父标签
考虑我在文件中有部分 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/