首页 > 解决方案 > 在 python 中寻找遍历 ElementTree.findall() 中所有嵌套标签的语法

问题描述

请忍受我,我正在xml挣扎ElementTreepython我已经发布了一个问题:如何使用 Element.findall() 搜索标签并打印其值并提供解决方案工作正常,但后来我意识到这是在标签namespace上注册的。<parent>我不知道那条数据会如何改变游戏计划。

<parent xmlns="http://xmlns.test.com/parent" version="1">

有了namespace,这findall('./*/c/d')不再是嵌套的tag(即c/d)。在这里阅读更多线程,我意识到我必须namespace像这样添加前缀。

def search(root, wordToSearch):
  tags = root.findall('{http://xmlns.test.com/parent}first')
  print tags

上面的代码肯定会找到<first>标签,但是我希望有catch all类似 ( ) 这样的路径./*/c/d来遍历<first>然后<second>标签。

我担心的是将来xml可能会有third or even more标签<parent>。有没有办法可以在不使用lxml库的情况下完成它?顺便说一句 - 我有 python2.6.6和服务器我正在运行脚本2.7.18rhel

[更新]

幸运的是,我能够找到解决方案ElementTree 1.3

def search(root, wordToSearch):
   for child in root: # child represents first and second tag
     el = child.tag.split('}', 1)[1] # Remove namespace
     el_path = 'xmlns:{0}/xmlns:c/xmlns:d'.format(el)
     target_tags = root.findall(el_path, namespaces={'xmlns': 'http://...'})

标签: pythonxml

解决方案


这对你有用吗?

from bs4 import BeautifulSoup

def get_texts(root, tag_name):
    return [tag.get_text() for tag in root.find_all(tag_name)]

soup = BeautifulSoup(open('test.xml').read(), features="lxml")
print(get_texts(soup, 'd'))
print(get_texts(soup, 'f'))

输出:

['987', '345']
['xxx', 'yyy', 'zzz', 'ttt', 'hhh', 'www']

这是包:https ://pypi.org/project/beautifulsoup4/


推荐阅读