在按复合类名称搜索时,BeautifulSoup返回空列表

时间:2015-12-15 12:12:29

标签: python regex python-2.7 beautifulsoup html-parsing

使用正则表达式按复合类名称搜索时,BeautifulSoup返回空列表。

示例:

import re
from bs4 import BeautifulSoup

bs = 
    """
    <a class="name-single name692" href="www.example.com"">Example Text</a>
    """

bsObj = BeautifulSoup(bs)

# this returns the class
found_elements = bsObj.find_all("a", class_= re.compile("^(name-single.*)$"))

# this returns an empty list
found_elements = bsObj.find_all("a", class_= re.compile("^(name-single name\d*)$"))

我需要选择非常精确的课程。有什么想法吗?

2 个答案:

答案 0 :(得分:4)

不幸的是,当您尝试在包含多个类的类属性值上进行正则表达式匹配时,BeautifulSoup会将正则表达式分别应用于每个类。以下是有关该问题的相关主题:

这都是因为class is a very special multi-valued attribute并且每次解析HTML时,其中一个BeautifulSoup树构建器(取决于解析器选择)在内部将类字符串值拆分为一个列表类(引自HTMLTreeBuilder的文档字符串):

# The HTML standard defines these attributes as containing a
# space-separated list of values, not a single value. That is,
# class="foo bar" means that the 'class' attribute has two values,
# 'foo' and 'bar', not the single value 'foo bar'.  When we
# encounter one of these attributes, we will parse its value into
# a list of values if possible. Upon output, the list will be
# converted back into a string.

有多种解决方法,但这里有一个hack-ish - 我们要求BeautifulSoup不要通过创建简单的自定义树构建器来处理class作为多值属性:< / p>

import re

from bs4 import BeautifulSoup
from bs4.builder._htmlparser import HTMLParserTreeBuilder


class MyBuilder(HTMLParserTreeBuilder):
    def __init__(self):
        super(MyBuilder, self).__init__()

        # BeautifulSoup, please don't treat "class" specially
        self.cdata_list_attributes["*"].remove("class")


bs = """<a class="name-single name692" href="www.example.com"">Example Text</a>"""
bsObj = BeautifulSoup(bs, "html.parser", builder=MyBuilder())
found_elements = bsObj.find_all("a", class_=re.compile(r"^name\-single name\d+$"))

print(found_elements)

在这种情况下,正则表达式将作为一个整体应用于class属性值。

或者,您只需解析启用了xml功能的HTML(如果适用):

soup = BeautifulSoup(data, "xml")

您还可以使用CSS selectors并将所有元素与name-single类匹配,并使用&#34;名称&#34;:

soup.select("a.name-single,a[class^=name]")

然后,您可以根据需要手动应用正则表达式:

pattern = re.compile(r"^name-single name\d+$")
for elm in bsObj.select("a.name-single,a[class^=name]"):
    match = pattern.match(" ".join(elm["class"]))
    if match:
        print(elm)

答案 1 :(得分:1)

对于这个用例,我只想使用custom filter,如下所示:

import re

from bs4 import BeautifulSoup
from bs4.builder._htmlparser import HTMLParserTreeBuilder

def myclassfilter(tag):
    return re.compile(r"^name\-single name\d+$").search(' '.join(tag['class']))

bs = """<a class="name-single name692" href="www.example.com"">Example Text</a>"""
bsObj = BeautifulSoup(bs, "html.parser")
found_elements = bsObj.find_all(myclassfilter)

print(found_elements)