如何使用 if in Python 检查 bs4 元素的类型?

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

当我检查 BeautifulSoup 元素的 type() 时,它会打印 <class 'bs4.element.Tag'>.

如何使用 if 检查变量的类型是否为 <class 'bs4.element.Tag'>

我尝试了以下两种方法,但是即使 bs4_element_var 的类型是 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")

您还必须将 TagBeautifulSoup 一起导入:

from bs4 import BeautifulSoup, Tag

并检查您的元素是否属于 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")