【发布时间】:2018-05-31 12:28:11
【问题描述】:
我正在使用Beautiful Soup 4 来解析和修改一组 HTML 文件。 HTML 文件是 Angular 模板,这意味着它们的标记与常规 HTML 文档中的标记有所不同(混合大小写属性、指令、输入/输出绑定等)。
Beautiful Soups documentation (html.parser, lxml, html5lib) 中列出的解析器没有一个完全符合我的需求。最接近它的是 Python 内置的 html.parser,但我不得不对其进行一些调整。
是否可以在 Beautiful Soup 中使用自定义解析器类?如果是,如何实现?
编辑: 下面是 Beautiful Soup 如何解析模板的示例。主要问题是结果中的所有属性都是小写的(*ngIf -> *ngif),并且指令(appAutoFocus、appKeepFocusInside 等)得到一个空字符串值(例如 appautofocus="")。
from bs4 import BeautifulSoup
test_html = """
<kendo-dialog *ngIf="dialogOpened" appAutoFocus appKeepFocusInside (close)="closeDialog()" width="1000">
<kendo-dialog-titlebar>A title</kendo-dialog-titlebar>
<div *ngIf="model.showValidationFailedMessage" class="alert alert-danger alert-dismissible">
<button type="button" class="close" aria-label="Close" (click)="model.closeValidationAlert()"><span
aria-hidden="true">&times;</span></button>
Validation failed
</div>
<kendo-tabstrip [keepTabContent]="true">
<kendo-tabstrip-tab title="Tab title 1" [selected]="true">
<ng-template kendoTabContent>
<div>Tab content</div>
</ng-template>
</kendo-tabstrip-tab>
</kendo-tabstrip>
</kendo-dialog>
"""
document = BeautifulSoup(test_html, "html.parser")
print(document.prettify())
结果:
<kendo-dialog (close)="closeDialog()" *ngif="dialogOpened" appautofocus="" appkeepfocusinside="" width="1000">
<kendo-dialog-titlebar>
A title
</kendo-dialog-titlebar>
<div *ngif="model.showValidationFailedMessage" class="alert alert-danger alert-dismissible">
<button (click)="model.closeValidationAlert()" aria-label="Close" class="close" type="button">
<span aria-hidden="true">
&times;
</span>
</button>
Validation failed
</div>
<kendo-tabstrip [keeptabcontent]="true">
<kendo-tabstrip-tab [selected]="true" title="Tab title 1">
<ng-template kendotabcontent="">
<div>
Tab content
</div>
</ng-template>
</kendo-tabstrip-tab>
</kendo-tabstrip>
</kendo-dialog>
【问题讨论】:
-
您是否尝试使用 BS 和 angular ?你有问题吗?在示例中显示它。
-
@furas 我在帖子中添加了一个示例。
标签: python python-3.x parsing beautifulsoup html-parsing