【问题标题】:What is the difference between "class" and "class_" in Python?Python中的“class”和“class_”有什么区别?
【发布时间】:2021-09-04 05:55:53
【问题描述】:
tags = soup.find_all(class='sister')
for tag in tags:
    print(tag)

在带有bs4的python中,当我在上面编写这段代码时,我找到了我的输出

错误无效语法“类”

如果我在类“class_”中使用下划线 (_),那么它可以工作。

【问题讨论】:

  • 你真的想不出class这个词在Python中的特殊含义吗?并且您正在尝试使用第三方库连接到 Internet 并分析数据?请确保您首先了解该语言的基础知识。
  • 另外,如果您尝试将python syntax class 放入搜索引擎会发生什么?

标签: python python-3.x beautifulsoup


【解决方案1】:
  • class(无下划线)是 Python 中的 reserved keywords 之一:

    以下标识符用作保留字,或语言的关键字,不能用作普通标识符:

    False      await      else       import     pass
    None       break      except     in         raise
    True       class      finally    is         return
    and        continue   for        lambda     try
    as         def        from       nonlocal   while
    assert     del        global     not        with
    async      elif       if         or         yield
    
  • class_(带下划线)一般没有特殊含义。 bs4 只是想要一个 CSS“类”参数,但 class 被保留 so they chose class_ with an underscore:

    使用class 作为关键字参数会导致语法错误。从 Beautiful Soup 4.1.2 开始,您可以使用关键字参数 class_ 按 CSS 类进行搜索:

    soup.find_all("a", class_="sister")
    

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-12-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-07
    • 1970-01-01
    • 2013-02-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多