我昨天安装了 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/