【发布时间】:2011-08-18 00:22:13
【问题描述】:
我有一个 html 文件,其中包含一些看起来像这样的文本(通过lxml.html parse、lxml.html clean 运行后,这是etree.tostring(table, pretty_print=True) 的结果)
<tr><td>
224
9:00 am
-3:00 pm
NPHC Leadership</td>
<td>
<font>ALSO IN 223; WALL OPEN</font></td>
我在 lxml 上找到的文档有点 spotty。我已经能够做很多事情来达到这一点,但我想做的是去掉除<table>、<td> 和<tr> 之外的所有标签。我还想从这些标签中去除所有属性,并且我还想摆脱实体,例如&#13;。
剥离我当前使用的属性:
etree.strip_attributes(tree, 'width', 'href', 'style', 'onchange',
'ondblclick', 'class', 'colspan', 'cols',
'border', 'align', 'color', 'value',
'cellpadding', 'nowrap', 'selected',
'cellspacing')
效果很好,但似乎应该有更好的方法。似乎应该有一些相当简单的方法来做我想做的事,但我找不到任何适合我的例子。
我尝试使用Cleaner,但是当我通过allow_tags时,像这样:
错误:Cleaner(allow_tags=['table', 'td', 'tr']).clean_html(tree) 它给了我这个错误:
ValueError: It does not make sense to pass in both allow_tags and remove_unknown_tags。此外,当我添加 remove_unkown_tags=False 时,我收到此错误:
Traceback (most recent call last):
File "parse.py", line 73, in <module>
SParser('schedule.html').test()
File "parse.py", line 38, in __init__
self.clean()
File "parse.py", line 42, in clean
Cleaner(allow_tags=['table', 'td', 'tr'], remove_unknown_tags=False).clean_html(tree)
File "/usr/lib/python2.6/dist-packages/lxml/html/clean.py", line 488, in clean_html
self(doc)
File "/usr/lib/python2.6/dist-packages/lxml/html/clean.py", line 390, in __call__
el.drop_tag()
File "/usr/lib/python2.6/dist-packages/lxml/html/__init__.py", line 191, in drop_tag
assert parent is not None
AssertionError
所以,总结一下:
- 我要删除 HTML 实体,例如
&#13; - 我想删除除
<table>、<tr>和<td>之外的所有标签 - 我想删除剩余标签中的所有属性。
任何帮助将不胜感激!
【问题讨论】:
-
使用 BeautifullSoup 会很好。
标签: python html-parsing lxml