python - BeautifulSoup 4.0b 标记按摩

标签 python python-3.x beautifulsoup

我昨天安装了 BeautifulSoup 4.0b,现在我想添加一个将在预解析阶段运行的正则表达式替换对。在文档中它说我可以简单地使用 markupMassage 参数到 __init__ 分配给 MARKUP_MASSAGE,但似乎 4.0b 不再有这些属性,尽管在 README 中没有提到它(除非我错过了?)。

所以我的问题是,有没有办法从 BeautifulSoup 4.0b 获得同样的功能

最佳答案

自述文件确实(某种程度上)涵盖了这个问题,但必须通过阅读本节的字里行间来推断:

= About Beautiful Soup 4 =

This is a nearly-complete rewrite that removes Beautiful Soup's custom HTML parser in favor of a system that lets you write a little glue code and plug in any HTML or XML parser you want.

Beautiful Soup 4.0 comes with glue code for four parsers:

  • Python's standard HTMLParser
  • lxml's HTML and XML parsers
  • html5lib's HTML parser

HTMLParser is the default, but I recommend you install one of the other parsers, or you'll have problems handling real-world markup.

旧的自定义解析器基于已弃用的 sgmllib 中的 SGMLParser模块(已在 Python 3 中删除),markupMassage 功能主要用于修复 SGMLParser 无法处理的无效标记。因此,当旧的自定义解析器消失时,markupMassage 功能也随之消失。

据推测,任何不再默认提供的功能现在都必须通过子类化其中一个新解析器来添加。

因此,如果安装了 lxml,您需要执行如下操作:

from bs4.builder import LXMLTreeBuilder

class Builder(LXMLTreeBuilder):
    def __init__(self, *args, **kwargs):
        super(Builder, self).__init__(*args, **kwargs)

    def prepare_markup(self, *args, **kwargs):

        markup, user_enc, doc_enc = super(Builder, self).prepare_markup(*args, **kwargs)

        # do markup massaging ...

        return markup, user_enc, doc_enc

soup = BeautifulSoup(html, builder=Builder())

关于python - BeautifulSoup 4.0b 标记按摩,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8626554/

相关文章:

python - 如何分发适用于 Mac OS 的应用程序,以便双击即可运行该应用程序?

python - Tornado Python - 流式传输视频

javascript - 我能用 BeautifulSoup 在 javascript 后面得到一个 iframe 吗?

python - 导入 hdbscan 时出现类型错误问题

python - fatal error : Python. h:没有这样的文件或目录

python - 自己编写的 os.walk-alike 比 os.walk 本身慢得多 - 为什么?

python - 使用正则表达式时得到不正确的匹配

python - Beautifulsoup4 没有为 pipenv 安装

android - 如何为 Kivy 中的按钮添加功能

python - 保留数据框中出现在列表中的行