【发布时间】:2011-10-15 04:46:02
【问题描述】:
我正在从页面中获取第一段并尝试提取适合作为标签或关键字的单词。在某些段落中有链接,我想删除标签:
例如,如果文本是
A <b>hex triplet</b> is a six-digit, three-<a href="/wiki/Byte"
enter code heretitle="Byte">byte</a> ...
我要删除
<b></b><a href="/wiki/Byte" title="Byte"></a>
到此结束
A hex triplet is a six-digit, three-byte ...
这样的正则表达式不起作用:
>>> text = """A <b>hex triplet</b> is a six-digit, three-<a href="/wiki/Byte"
enter code heretitle="Byte">byte</a> ..."""
>>> f = re.findall(r'<.+>', text)
>>> f
['<b>hex triplet</b>', '</a>']
>>>
最好的方法是什么?
我发现了几个类似的问题,但我认为没有一个可以解决这个特定问题。
使用 BeautifulSoup 提取示例进行更新(提取删除包含其文本的标签,并且必须为每个标签单独运行:
>>> soup = BeautifulSoup(text)
>>> [s.extract() for s in soup('b')]
[<b>hex triplet</b>]
>>> soup
A is a six-digit, three-<a href="/wiki/Byte" enter code heretitle="Byte">byte</a> ...
>>> [s.extract() for s in soup('a')]
[<a href="/wiki/Byte" enter code heretitle="Byte">byte</a>]
>>> soup
A is a six-digit, three- ...
>>>
更新
对于有同样问题的人:正如 Brendan Long 所说,this answer 使用 HtmlParser 效果最好。
【问题讨论】:
-
另见Parsing Html the Cthulu Way。简短版本:不要使用正则表达式。
-
尝试 lxml 模块(参见 lxml.de)使用 lxml 很简单
-
@BrendanLong:感谢这个链接stackoverflow.com/questions/753052/… 它很好用