Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check element type in BeautifulSoup 3

How can I check if a Tag element is of a certain type, for example a div, in BS3?

like image 990
8vius Avatar asked Mar 21 '14 17:03

8vius


People also ask

How do you find elements using BeautifulSoup?

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.

What is Find () method in BeautifulSoup?

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.

Is bs4 same as BeautifulSoup?

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.


1 Answers

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.

like image 74
Martijn Pieters Avatar answered Oct 04 '22 04:10

Martijn Pieters