python bs4分析器类中的错误?

时间:2014-01-08 11:04:03

标签: python regex beautifulsoup

#!/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中删除。但是这段代码由于某种原因不起作用!

1 个答案:

答案 0 :(得分:2)

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()