python - Python3中方法has_key的替换

标签 python python-3.x python-2.7 beautifulsoup web-crawler

我想改变这个

def has_class_but_no_id(tag):
    return tag.has_key('class') and not tag.has_key('id')

此函数来自 Python2,不适用于 Python3

我以为

我在这样的列表中更改了这个 HTML 文档

list_of_descendants = list(soup.descendants)

所以我可以获得包含类但不包含 id 的标签 它是关于找到所有带有 class = blabla... 但不是 id = ... 的标签 我不知道如何处理这个问题

最佳答案

documentation说:

I renamed one method for compatibility with Python 3:

  • Tag.has_key() -> Tag.has_attr()

此外,documentation here 中提供了完全相同的功能。 :

If none of the other matches work for you, define a function that takes an element as its only argument. The function should return True if the argument matches, and False otherwise.

Here’s a function that returns True if a tag defines the “class” attribute but doesn’t define the “id” attribute:

def has_class_but_no_id(tag):
    return tag.has_attr('class') and not tag.has_attr('id')

关于python - Python3中方法has_key的替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49683817/

相关文章:

Python,删除UTF8 MySQL DB无法处理的字符,例如表情符号

python - UnicodeDecodeError : 'utf-8' codec can't decode byte 0xe2 in position 1023: unexpected end of data

python - 在 Python 中与 os.system() 并行运行两个可执行文件?

python - 在 Python 中子类化特定异常的缺点?

python - 使用 .json() 格式化性能问题

mysql - 如何用python连接Google云存储数据库

python - 无法在 Python 3 (OSX) 中导入蓝牙

python - psutil 的构建轮失败

python - 导入错误 : no module named transaction

python - 如何从 django 模板在 html 页面上打印漂亮的 JSON?