【发布时间】:2015-12-09 23:03:46
【问题描述】:
我正在使用 python 和 BeautifulSoup 解析许多大型 XML 文件。我经常遇到以下任务:
<Section1>
<Report>
<Matrix>...</Matrix>
<Matrix>...</Matrix>
<Matrix>...</Matrix>
<Matrix>...</Matrix>
</Report>
</Section1>
我正在尝试收集并遍历所有矩阵。我使用如下代码:
res = urlopen(url)
html = res.read()
soup = BeautifulSoup(html, 'xml')
matrices = soup.find("Section1").find_all("Matrix")
#Then I handle each matrix
为什么我不能使用这样的选择器?
matrices = soup.find("Section1 Matrix")
有没有更快的方法来做到这一点?有时我访问嵌套在 XML 中更远的节点,我需要确保它们是后代,但不一定是其他几个节点的直接子节点。提供的示例是一个简化。任何帮助将不胜感激。
【问题讨论】:
-
你试过使用lxml吗?它将大大提高性能。
标签: python xml css-selectors beautifulsoup