BeautifulSoup 按复合类名搜索时返回空列表 [英] BeautifulSoup returns empty list when searching by compound class names
问题描述
使用正则表达式按复合类名称搜索时,BeautifulSoup 返回空列表.
BeautifulSoup returns empty list when searching by compound class names using regex.
示例:
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 named*)$"))
我需要非常精确的类选择.有什么想法吗?
I need the class selection to be very precise. Any ideas?
推荐答案
不幸的是,当您尝试对包含多个类的类属性值进行正则表达式匹配时,BeautifulSoup
会应用正则表达式分别表达到每个类.以下是有关该问题的相关主题:
Unfortunately, when you try to make a regular expression match on a class attribute value that contains multiple classes, BeautifulSoup
would apply the regular expression to every single class separately. Here are the relevant topics about the problem:
这都是因为class
是一个非常特殊的多值属性,每次解析 HTML 时,BeautifulSoup
的树构建器之一(取决于解析器选择)在内部拆分类字符串value 到一个类列表中(引用自 HTMLTreeBuilder
的文档字符串):
This is all because class
is a very special multi-valued attribute and every time you parse HTML, one of the BeautifulSoup
's tree builders (depending on the parser choice) internally splits a class string value into a list of classes (quote from the HTMLTreeBuilder
's docstring):
# 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
作为多值属性处理简单的自定义树生成器:
There are multiple workarounds, but here is a hack-ish one - we are going to ask BeautifulSoup
not to handle class
as a multi-valued attribute by making our simple custom tree builder:
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 named+$"))
print(found_elements)
在这种情况下,正则表达式将作为一个整体应用于 class
属性值.
In this case the regular expression would be applied to a class
attribute value as a whole.
或者,您可以在启用 xml
功能的情况下解析 HTML(如果适用):
Alternatively, you can just parse the HTML with xml
features enabled (if this is applicable):
soup = BeautifulSoup(data, "xml")
<小时>
您还可以使用 CSS 选择器 并匹配具有 name-single
类和以name"开头的类的所有元素:
You can also use CSS selectors and match all elements with name-single
class and a class staring with "name":
soup.select("a.name-single,a[class^=name]")
然后您可以根据需要手动应用正则表达式:
You can then apply the regular expression manually if needed:
pattern = re.compile(r"^name-single named+$")
for elm in bsObj.select("a.name-single,a[class^=name]"):
match = pattern.match(" ".join(elm["class"]))
if match:
print(elm)
这篇关于BeautifulSoup 按复合类名搜索时返回空列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!