working heavily with BeautifulSoup 4.9.3 under python 3.9.2. anyway, is there a property for each Tag or NavigableString where we can get the depth or level of the Tag, for instance? like html would be level 0 and head and body would be 1, and the title or first div would be 2, and so forth. would really help ground the computations if that were a property. and the depth property would also be automatically updated if the tree were modified, like by wrap or unwrap, etc.
if the depth property is there and i'm not aware of it, please share. if not, please add this property to a future version. thank you in advance and have a good day. lucas
ok, so I've been thinking about this and if its a get, read, only property on an object, then it would be easy to add the code to calculate the depth on the fly by simply using the .parents property for the Tag or NavigableString. for instance, [e.name for e in tag.parents] would return ['body', 'html', '[document]'] and thus the len()-1 of that would yield the depth.
wherein the depth method would be something like:
def get_depth(__self__):
return len(__self__.parents)-1
def get_depth(__self__):
return len([t.name for t in __self__.parents])
should return the proper proposed depths.--
You received this message because you are subscribed to the Google Groups "beautifulsoup" group.
To unsubscribe from this group and stop receiving emails from it, send an email to beautifulsou...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/beautifulsoup/6b2fbad4-ea8d-4d95-9b05-c4e9769fe5a1n%40googlegroups.com.
It’s probably quicker to just do:
len(list(el.parents))
It’s also pretty trivial enough that I’m not sure it needs a property, but if one was added, I’d imagine the above would be quicker.