BeautifulSoup returns 按化合物 class 名称搜索时为空列表

BeautifulSoup returns empty list when searching by compound class names

BeautifulSoup returns 使用正则表达式按化合物 class 名称搜索时为空列表。

示例:

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*)$"))

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

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

这都是因为 class is a very special multi-valued attribute 并且每次您解析 HTML 时,BeautifulSoup 的树构建器之一(取决于解析器的选择)在内部拆分 class 字符串值到 classes 的列表中(引用自 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 作为多值属性处理,方法是制作我们简单的自定义树构建器:

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 class 和 class 以 "name":

开头匹配
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)

对于这个用例,我会简单地使用 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)