pythonbeautifulsoupvariable-types

How to check a bs4 element's type with if in Python?


When I check the type() of a BeautifulSoup element, it prints <class 'bs4.element.Tag'>.

How do I check if a variable's type is of <class 'bs4.element.Tag'> using if?

I tried both of the below methods, but it never worked even though the type of the bs4_element_var is bs4.element.Tag.

if type(bs4_element_var) == bs4.element.Tag:
    print("bs4_element_var's type is bs4.element.Tag")

if isinstance(bs4_element_var, bs4.element.Tag)
    print("bs4_element_var's type is bs4.element.Tag")

Solution

  • You have to also import the Tag together with BeautifulSoup:

    from bs4 import BeautifulSoup, Tag
    

    and check if your elements is of type() Tag:

    if type(bs4_element_var) == Tag:
        print("bs4_element_var's type is bs4.element.Tag")
    
    if isinstance(bs4_element_var, Tag):
        print("bs4_element_var's type is bs4.element.Tag")