问题描述
有没有办法找到在Python使用非递归DOM子节点?
Is there any way to find a nonrecursive DOM subnode in Python using BeautifulSoup
?
例如。考虑解析的pom.xml
文件:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<parent>
<groupId>com.parent</groupId>
<artifactId>parent</artifactId>
<version>1.0-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>2.0.0</modelVersion>
<groupId>com.parent.somemodule</groupId>
<artifactId>some_module</artifactId>
<packaging>jar</packaging>
<version>1.0-SNAPSHOT</version>
<name>Some Module</name>
...
如果我想获得的groupId
在顶层(特别是项目 - &GT;的groupId
,而不是项目 - &GT;父 - &GT;的groupId
),我使用的:
If I want to get groupId
at the top level (specifically project->groupId
, not project->parent->groupId
), I use:
with open(pom) as pomHandle:
soup = BeautifulSoup(pomHandle)
groupId = soup.groupid.text
但不幸的是,不管层次的水平,这是发现的文件中的groupId
的第一个物理出现项目 - &GT;父 - &GT;的groupId
。其实我想做一个unrecursive发现只有在特定的节点级别,而不是在它的孩子。有没有办法做到这一点在 BeautifulSoup
?
But unfortunately, that finds the first physical occurrence of groupId
in the file regardless of the hierarchy level, which is project->parent->groupId
. I actually want to do a unrecursive find ONLY at a specific node level, not within its children. Is there a way to do it in BeautifulSoup
?
推荐答案
您可以搜索里面的项目节点与递归=假
:
You can search inside "project" node with recursive=False
:
groupId = soup.project.find('groupid', recursive=False).text
希望有所帮助。
这篇关于查找使用BeautifulSoup的Python非递归DOM子节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!