python - BeautifulSoup 中带有 .get-operator 的 if 语句

标签 python html python-3.x html-parsing beautifulsoup

我正在尝试获取 dl 元素的类。我可以打印该类(请参阅第一行),但我无法在 if 语句中使用该结果(因此永远不会打印“works”)。 我想我的语法有些错误。我是吗? 相信我,我的测试中有很多“方法”类元素 - 见下文

 print(child.dl.get('class'))
    if child.dl.get('class')=="['method']":
        print("WORKS!")

这是第一行的输出:

['method']
['method']
['class']
['method']
['method']
['method']
['method']
['describe']

最佳答案

child.dl.get('class') 返回一个 list 因为 classmulti-valued attribute .

检查方法是否在列表内:

if 'method' in child.dl.get('class', []):
    print("WORKS!")

关于python - BeautifulSoup 中带有 .get-operator 的 if 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23224802/

相关文章:

python - 使用 webpy 线程化特定数据

python - 使用 Gitlab 的 CI : QXcbConnection error 在 PyQt5 中自动化单元测试

javascript - 如何仅在 javascript 中的 onclick 上播放 gif

javascript - jquery动态下拉列表

python - 使用 TCP 同时在两个进程之间进行多处理连接

python - 同一进程中非常简单的 python-dbus 服务器/客户端

html - 在格式化 HTML 文档时,我无法让 <cite> 文本正确对齐

Python 3 - ValueError : not enough values to unpack (expected 3, 得到 2)

python-3.x - 在Linux中创建一个后台运行的进程

python - 一种更简洁的方法来尝试 try except in python