如何在BeautifulSoup4中获取标签多类名并解决NoneType下标报错
问题原因
你在代码中尝试从<p>标签提取class属性,但传入的HTML结构中不存在<p>标签,只有<span>标签。contendorTipo.p会返回None,对None执行下标取值操作就会触发对应的TypeError。
解决方法
bs4会自动将多值的class属性解析为列表,你只需要先正确选中<span>标签,再提取属性即可,示例代码如下:
from bs4 import BeautifulSoup contendorTipo = BeautifulSoup('<span class="type Manhwa"></span>', 'html.parser') # 选中span标签后提取class属性 class_list = contendorTipo.span['class'] # 取第二个类名(列表索引从0开始计数) second_class = class_list[1] print(second_class)
运行上述代码会输出你需要的第二个类名Manhwa。
如果需要提高代码健壮性,避免标签不存在、无class属性、class数量不足2个导致的报错,可以增加判空逻辑:
span_tag = contendorTipo.span if span_tag and 'class' in span_tag.attrs and len(span_tag['class'])>=2: second_class = span_tag['class'][1] print(second_class)
内容的提问来源于stack exchange,提问作者lilithkms
相关产品推荐
相关产品推荐

