Py学习  »  Python

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

Justin M • 3 年前 • 1150 次点击  

当我检查 type() 一个美丽的元素,它打印 <class 'bs4.element.Tag'> .

如何检查变量的类型是否为 <班上的bs4。要素标签“> 使用 if ?

我尝试了以下两种方法,但都不管用,尽管 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")
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/130986
 
1150 次点击  
文章 [ 1 ]  |  最新文章 3 年前
MendelG
Reply   •   1 楼
MendelG    4 年前

您还必须导入 Tag 连同 BeautifulSoup :

from bs4 import BeautifulSoup, Tag

检查你的元素是否正确 type() 标签 :

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")