How can I check if a Tag
element is of a certain type, for example a div
, in BS3?
Beautiful Soup provides "find()" and "find_all()" functions to get the specific data from the HTML file by putting the specific tag in the function. find() function - return the first element of given tag. find_all() function - return the all the element of given tag.
find() method The find method is used for finding out the first tag with the specified name or id and returning an object of type bs4. Example: For instance, consider this simple HTML webpage having different paragraph tags.
As BeautifulSoup is not a standard python library, we need to install it first. We are going to install the BeautifulSoup 4 library (also known as BS4), which is the latest one.
You are looking for the tag name:
if element.name == 'div':
Demo:
>>> from bs4 import BeautifulSoup
>>> soup = BeautifulSoup('<div><span></span></div>')
>>> print soup.find('div').name
div
This attribute hasn't changed between BeautifulSoup 3 and 4. I strongly recommend you use BeautifulSoup 4; all development on BS3 has stopped, the last release for that version was over 2 years ago.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With