Test If Children Tag Exists In Beautifulsoup
i have an XML file with an defined structure but different number of tags, like file1.xml: 1 1
Solution 1:
if tag.find('child_tag_name'):
Solution 2:
The simplest way to find if a child tag exists is simply
childTag = xml.find('childTag')
if childTag:
# do stuff
More specifically to OP's question:
If you don't know the structure of the XML doc, you can use the .find()
method of the soup. Something like this:
with open("file1.xml",'r') asdata, open("file2.xml",'r') as data2:
xml = BeautifulSoup(data.read())
xml2 = BeautifulSoup(data2.read())
hasAttrBs = xml.find("myId")
hasAttrBs2 = xml2.find("myId")
If you do know the structure, you can get the desired element by accessing the tag name as an attribute like this xml.document.subdoc.myid
. So the whole thing would go something like this:
withopen("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
Prints
<myid>1</myid>
None
Solution 3:
Here's an example to check if h2 tag exists in an Instagram URL. Hope you find it useful:
import datetime
import urllib
import requests
from bs4 importBeautifulSoupinstagram_url='https://www.instagram.com/p/BHijrYFgX2v/?taken-by=findingmero'
html_source = requests.get(instagram_url).textsoup= BeautifulSoup(html_source, "lxml")
if not soup.find('h2'):
print("didn't find h2")
Solution 4:
you can handle it like this:
for child in xml.document.subdoc.children:
if'myId' == child.name:
return True
Solution 5:
You can do it with if tag.myID:
If you want to check if myID
is the direct child not child of child use if tag.find("myID", recursive=False):
If you want to check if tag has no child, use if tag.find(True):
Post a Comment for "Test If Children Tag Exists In Beautifulsoup"