测试美化组中是否存在子标记

2024-06-26 14:32:00 发布

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

我有一个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>的属性。

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

//Edit:顺便说一句:我不太喜欢遍历整个子文档,因为那样会非常慢。我希望能找到一种方法来直接向那个元素发问。


Tags: 文件标记idfalsedatatypexmldocument
3条回答

下面是一个检查Instagram URL中是否存在h2标记的示例。希望你觉得有用:

import datetime
import urllib
import requests
from bs4 import BeautifulSoup

instagram_url = 'https://www.instagram.com/p/BHijrYFgX2v/?taken-by=findingmero'
html_source = requests.get(instagram_url).text
soup = BeautifulSoup(html_source, "lxml")

if not soup.find('h2'):
    print("didn't find h2")

如果不知道XML文档的结构,可以使用soup的.find()方法。像这样的:

with open("file1.xml",'r') as data, open("file2.xml",'r') as data2:
    xml = BeautifulSoup(data.read())
    xml2 = BeautifulSoup(data2.read())

    hasAttrBs = xml.find("myId")
    hasAttrBs2 = xml2.find("myId")

如果您确实知道这个结构,那么可以通过将标记名作为类似于xml.document.subdoc.myid的属性访问来获得所需的元素。所以整件事都是这样的:

with open("file1.xml",'r') as data, open("file2.xml",'r') as data2:
    xml = BeautifulSoup(data.read())
    xml2 = BeautifulSoup(data2.read())

    hasAttrBs = xml.document.subdoc.myid
    hasAttrBs2 = xml2.document.subdoc.myid
    print hasAttrBs
    print hasAttrBs2

印刷品

<myid>1</myid>
None
if tag.find('child_tag_name'):

相关问题 更多 >