The Bndr The Bndr - 1 year ago 264
Python Question

Test if children tag exists in beautifulsoup

i have an XML file with an defined structure but different number of tags, like





Now i like to check, if the tag
exits. So i did the following:

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)

The result is for

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


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

is not an attribute of

But how i can test, if an sub-tag exists?

//Edit: By the way: I'm don't really like to iterate trough the whole subdoc, because that will be very slow. I hope to find an way where I can direct address/ask that element.

Answer Source

You can get this by accessing the tag name as an attribute like this xml.document.subdoc.myid. So the whole thing would go something like this:

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

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


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download