【问题标题】:Disable special "class" attribute handling禁用特殊的“类”属性处理
【发布时间】: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


【解决方案1】:

我不喜欢这种方法,因为它涉及导入“私有”内部_htmlparser 非常“不自然”和“神奇”。我希望有一个更简单的方法。

是的,您可以改为从 bs4.builder 导入它:

from bs4 import BeautifulSoup
from bs4.builder import HTMLParserTreeBuilder

class MyBuilder(HTMLParserTreeBuilder):
    def __init__(self):
        super(MyBuilder, self).__init__()
        # BeautifulSoup, please don't treat "class" as a list
        self.cdata_list_attributes["*"].remove("class")


soup = BeautifulSoup(data, "html.parser", builder=MyBuilder())

如果它足够重要以至于您不想重复自己,请将构建器放在它自己的模块中,并使用register_treebuilders_from() 注册它,以便它优先。

【讨论】:

  • 虽然这可行,但我讨厌我的 IDE(带有 Python 插件的 PyCharm 和 IntelliJ IDEA)抱怨 bs4.builder 导入。他们说“未解析的引用'HTMLParserTreeBuilder'”,当我要求它时,它无法跳转到它的声明。其他 IDE 在这方面做得更好吗?
【解决方案2】:

HTMLParserTreeBuilder这个类实际上是在upper module_init__.py上声明的,所以不需要直接从私有子模块导入。那就是说我会这样做:

import re

from bs4 import BeautifulSoup
from bs4.builder import HTMLParserTreeBuilder

bb = HTMLParserTreeBuilder()
bb.cdata_list_attributes["*"].remove("class")

soup = BeautifulSoup(bs, "html.parser", builder=bb)
found_elements = soup.find_all(class_=re.compile(r"^name\-single name\d+$"))
print found_elements

这与在 OP 中定义类基本相同(可能更明确一点),但我认为没有更好的方法。

【讨论】:

    猜你喜欢
    • 2011-10-23
    • 2012-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多