gpt4 book ai didi

python - 测试 children 标签是否存在于 beautifulsoup 中

转载 作者:太空狗 更新时间:2023-10-29 17:39:38 25 4
gpt4 key购买 nike

我有一个具有定义结构但标签数量不同的 XML 文件,例如

文件1.xml:

<document>
<subDoc>
<id>1</id>
<myId>1</myId>
</subDoc>
</document>

文件2.xml:

<document>
<subDoc>
<id>2</id>
</subDoc>
</document>

现在我想检查,如果标签myId导出。所以我做了以下事情:

data = open("file1.xml",'r').read()
xml = BeautifulSoup(data)

hasAttrBs = xml.document.subdoc.has_attr('myID')
hasAttrPy = hasattr(xml.document.subdoc,'myID')
hasType = type(xml.document.subdoc.myid)

结果是文件 1.xml:

hasAttrBs -> False
hasAttrPy -> True
hasType -> <class 'bs4.element.Tag'>

文件2.xml:

hasAttrBs -> False
hasAttrPy -> True
hasType -> <type 'NoneType'>

好的,<myId>不是 <subdoc> 的属性.

但是如果存在子标签,我该如何测试呢?

//编辑:顺便说一下:我真的不喜欢遍历整个子文档,因为那样会很慢。我希望找到一种方法可以直接解决/询问该元素。

最佳答案

if tag.find('child_tag_name'):

关于python - 测试 children 标签是否存在于 beautifulsoup 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33238091/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com