【问题标题】:How to check a bs4 element's type with if in Python?如何在 Python 中使用 if 检查 bs4 元素的类型?
【发布时间】:2021-06-18 16:35:51
【问题描述】:

当我检查 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")

【问题讨论】:

  • @Iain 我已经尝试过“isinstance(bs4_element_var, bs4.element.Tag)”,但没有返回 True 或 False 值。我是不是用错了 isinstance() 函数?
  • isinstance 总是返回 True 或 False(或引发 TypeError)你是如何使用它的?应该类似于if isinstance(bs4_element_var, bs4.element.Tag):
  • @Iain 我将代码放在 try-except 中,结果我只从 bs4 导入 BeautifulSoup,因此引发了“名称 bs4 未定义”错误消息。当我导入整个 bs4 包时它可以工作。谢谢。

标签: python beautifulsoup variable-types


【解决方案1】:

您还必须将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")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-27
    • 2013-09-19
    • 1970-01-01
    • 1970-01-01
    • 2019-05-10
    • 2018-06-30
    相关资源
    最近更新 更多