【问题标题】:if-statement with .get-operator in BeautifulSoupBeautifulSoup 中带有 .get-operator 的 if 语句
【发布时间】:2014-06-07 03:14:58
【问题描述】:

我正在尝试获取 dl 元素的类。我可以打印课程(见第一行),但我不能在 if 语句中使用该结果(所以永远不会打印“作品”)。 我想我的语法有点错误。我是吗? 相信我,我的测试中有很多“方法”类元素 - 见下文

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

这是第一行的输出:

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

【问题讨论】:

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


    【解决方案1】:

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

    检查method 是否在列表中:

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

    【讨论】:

      猜你喜欢
      • 2012-01-27
      • 2016-08-15
      • 2014-10-26
      • 2018-02-20
      • 2018-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多