BeautifulSoup 4.0b markupMassag公司

2024-10-02 00:27:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我昨天安装了beauthoulsoup4.0b,现在我想添加一个regex替换对,它将在预解析器阶段运行。在文档中,它说我可以简单地将markupMassage参数用于分配给MARKUP_MASSAGE__init__,但似乎4.0b不再具有这些属性,尽管在自述文件中没有提到它(除非我错过了它?)。在

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


Tags: 文档功能解析器参数属性init自述文件阶段
1条回答
网友
1楼 · 发布于 2024-10-02 00:27:05

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

= 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(在python3中已删除)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())

相关问题 更多 >

    热门问题