首页 > 解决方案 > 如何在 BeautifulSoup4 中获取多个类名

问题描述

我在python中遇到了bs4的问题,在下面的代码中,我想知道标签中的第二个类名

HTML 代码:

<span class="type Manhwa"></span>

所以我写了这个

contendorTipo = BeautifulSoup('<span class="type Manhwa"></span>', 'html.parser')
tipo = contendorTipo.p['class']

在 bs4 文档示例(https://www.crummy.com/software/BeautifulSoup/bs4/doc/#multi-valued-attributes)中是这样写的

所以我希望控制台打印一个包含 2 个值(类型和 Manhwa)的数组或包含两个类的字符串,但是我在控制台中看到以下错误

TypeError: 'NoneType' object is not subscriptable

请帮助我!x'd

标签: pythonbeautifulsoup

解决方案


而不是p标签,你应该span在你的标签中使用classes

from bs4 import BeautifulSoup
contendorTipo = BeautifulSoup('<span class="type Manhwa"></span>', 'html.parser')
classes = contendorTipo.span['class']

classes

输出:

['type', 'Manhwa']

推荐阅读