在Beautiful Soup中如何判断td标签对应的具体class属性值?
解决方案
核心错误说明
你之前使用has_attr()的方式不符合API规范,该方法仅接收单个属性名作为入参,仅能判断属性是否存在,无法校验属性值,也不支持传入标签名和属性字典的参数格式。
方案1:保持原有遍历逻辑,直接判断class属性值
BeautifulSoup的标签对象可通过get()方法获取指定属性的取值,其中class属性因支持多值,会自动返回列表格式,直接判断目标类名是否在列表中即可:
for tag in soup.find_all("td"): # 第二个参数为默认值,避免无class属性时报错 class_val = tag.get("class", []) if "search-detail-heading" in class_val: DoSomething() elif "search-detail-subject" in class_val: DoSomethingElse() # 可继续扩展其他class的处理逻辑
方案2:优化find_all调用,减少无效遍历
如果仅需要处理这两类class的td标签,可在find_all的入参中传入class列表,一次性筛选出所有目标标签,无需多次调用find_all:
# 一次性筛选两类目标td,排除无相关class的标签 for tag in soup.find_all("td", class_=["search-detail-heading", "search-detail-subject"]): class_val = tag.get("class", []) if "search-detail-heading" in class_val: DoSomething() elif "search-detail-subject" in class_val: DoSomethingElse()
注意事项
如果你的td标签存在单个标签绑定多个class的场景(比如<td class="search-detail-heading other-class">),上述用in判断的逻辑依然可以正常匹配,兼容性更强。
内容的提问来源于stack exchange,提问作者Birk
相关产品推荐
相关产品推荐

