Python Forum

Full Version: Check element for a particular type
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello,
When I print type of a particular element, the output is:
Output:
<class 'bs4.element.Tag'>
How to check it in condition statement ?
The following check
if type(aaa) == bs4.element.Tag:
doesn't work.
Any suggestions ?
Thanks.
Use isinstance and not type,from BS can import Tag element to compare against.
from bs4 import Tag, NavigableString, BeautifulSoup

html = '''\
<table class="table-info">
<tr>
    <td class="col-1"><div class="col-1-text">E-mail:</div></td>
    <td class="col-2"><div class="col-2-text"><a href="mailto:[email protected]">[email protected]</a></div></td>
</tr>
</table>'''

soup = BeautifulSoup(html, 'lxml')
 
Usage test.
>>> isinstance(soup, Tag)
True
>>> 
>>> s = 'hello'
>>> isinstance(s, Tag)
False
>>> 
>>> td = soup.select_one('.col-1')
>>> td
<td class="col-1"><div class="col-1-text">E-mail:</div></td>
>>> isinstance(td, Tag)
True
Works!
Thanks.