Python靓汤寻找标签最有效的方法

2024-04-20 09:13:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用python和beauthoulsoup解析许多大型XML文件。我经常遇到以下任务:

<Section1>
    <Report>
        <Matrix>...</Matrix>
        <Matrix>...</Matrix>
        <Matrix>...</Matrix>
        <Matrix>...</Matrix>
    </Report>
</Section1>

我试图收集和迭代所有的矩阵。我使用如下代码:

^{pr2}$

为什么我不能用这样的选择器?在

matrices = soup.find("Section1 Matrix")

有没有更快的方法?有时我访问的节点嵌套在XML中更远的地方,我需要确保它们是子节点,但不一定是其他几个节点的直接子节点。提供的示例a是一种简化。任何帮助都将不胜感激。在


Tags: 文件方法代码report节点选择器矩阵xml
1条回答
网友
1楼 · 发布于 2024-04-20 09:13:00

BeautifulSoup "supports CSS selectors"您需要将选择器传递给.select方法

In [1]: from bs4 import BeautifulSoup as BS

In [2]: soup = BS("""<Section1>
   ...:     <Report>
   ...:         <Matrix>...</Matrix>
   ...:         <Matrix>...</Matrix>
   ...:         <Matrix>...</Matrix>
   ...:         <Matrix>...</Matrix>
   ...:     </Report>
   ...: </Section1>""", "xml")

In [3]: soup.select("Section1 Matrix")
Out[3]: 
[<Matrix>...</Matrix>,
 <Matrix>...</Matrix>,
 <Matrix>...</Matrix>,
 <Matrix>...</Matrix>]

如果您希望获得文档中所有的Matrix节点,则可以使用 来自^{}1^{}类。在

^{pr2}$

1如果cssselect尚未与pip一起安装,则需要安装它:pip install cssselect

相关问题 更多 >