Skip to main content
 首页 » 编程设计

python之python bs4 分析器类中的错误

2024年11月01日8jyk

#!/usr/bin/env python 
# -*- coding: utf-8 -*- 
 
from bs4 import BeautifulSoup 
import re 
doc = "<div>Text text <span class='_ _3'>empty</span> text</div>" 
soup = BeautifulSoup(doc) 
for span in soup.find_all('span' , class_=re.compile("_\s_[0-9]+")) : 
    span.decompose() 

需要找到所有带<span class=_ _\d+>的标签并从 DOM 中移除。但是由于某种原因,这段代码无法正常工作!

请您参考如下方法:

BeautifulSoup 将类拆分成列表;正则表达式不会匹配多个类。 class 是一组这样的属性之一,参见 Multi-valued attributes .

您必须使用自定义函数来使用正则表达式过滤多个类:

def underscored_class_span(elem, numbered=re.compile(u'_\d').match): 
    if elem.name != 'span': return False 
    classes = elem.get('class', []) 
    return u'_' in classes and any(numbered(c) for c in classes) 
 
for span in soup.find_all(underscored_class_span): 
    span.decompose()