【发布时间】:2016-03-21 15:20:41
【问题描述】:
故事:
当您使用 BeautifulSoup 解析 HTML 时,class 属性被视为 multi-valued attribute 并以特殊方式处理:
请记住,单个标签的“类”属性可以有多个值。当您搜索与某个 CSS 类匹配的标签时,您将匹配其任何 CSS 类。
另外,来自BeautifulSoup 使用的内置HTMLTreeBuilder 的引用作为其他树构建器类的基础,例如HTMLParserTreeBuilder:
# 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.
问题:
如何配置BeautifulSoup 以将class 作为通常的单值属性处理?换句话说,我不希望它专门处理class 并将其视为常规属性。
仅供参考,这里有一个有用的用例:
我的尝试:
我实际上是通过创建一个自定义树构建器类并从特殊处理的属性列表中删除 class 使其工作的:
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")
soup = BeautifulSoup(data, "html.parser", builder=MyBuilder())
我不喜欢这种方法,因为它涉及导入“私有”内部_htmlparser 非常“不自然”和“神奇”。我希望有一个更简单的方法。
注意:我想保存所有其他与 HTML 解析相关的功能,这意味着我不想用“xml”-only 功能解析HTML(这可能是另一种解决方法)。
【问题讨论】:
-
当我在一个没有答案的美丽汤问题下看到你的头像时,我认为这是一个错误,然后我意识到你问了这个问题!我无法为您提供帮助,我尝试的所有方法均无效或涉及两次迭代。
-
我不知道该怎么做,但是对于作为示例提供的特定用例,我提供了不同的答案(所以我把它贴在那里)。我认为它更简单,但对于其他用例可能还不够
-
将其用作 CSS 选择器?也许在那种情况下,最简单的选择可能是不使用通用类选择器,而是使用属性选择器。选择器 '.myclass' 与 '[class=~"myclass"]' 相同,但选择器 '[class="class"]' 是一个元素,其 "class" 属性值正好等于 "myclass"(不是myclass 在一个空格分隔的列表中)。
-
@miguel-svq 好点,CSS 选择器可能会有所帮助,具体取决于用例。如果我们从链接的问题中获取该用例,则会将正则表达式模式应用于类属性 - 这是我们无法通过 CSS 选择器真正实现的功能,但是,我们可以使用它们来缩小搜索范围,然后进行一些手动操作检查。谢谢!
标签: python html beautifulsoup html-parsing