我已經在過去做了一些研究,最後在Python中實現this approach [pdf]。我實現的最終版本在應用算法之前也做了一些清理,例如刪除head/script/iframe元素,隱藏元素等,但這是它的核心。
這是一個帶有「鏈接列表」鑑別器(非常)天真實現的功能,它試圖移除鏈接到文本比例較大的元素(即導航欄,菜單,廣告等):
def link_list_discriminator(html, min_links=2, ratio=0.5):
"""Remove blocks with a high link to text ratio.
These are typically navigation elements.
Based on an algorithm described in:
http://www.psl.cs.columbia.edu/crunch/WWWJ.pdf
:param html: ElementTree object.
:param min_links: Minimum number of links inside an element
before considering a block for deletion.
:param ratio: Ratio of link text to all text before an element is considered
for deletion.
"""
def collapse(strings):
return u''.join(filter(None, (text.strip() for text in strings)))
# FIXME: This doesn't account for top-level text...
for el in html.xpath('//*'):
anchor_text = el.xpath('.//a//text()')
anchor_count = len(anchor_text)
anchor_text = collapse(anchor_text)
text = collapse(el.xpath('.//text()'))
anchors = float(len(anchor_text))
all = float(len(text))
if anchor_count > min_links and all and anchors/all > ratio:
el.drop_tree()
在我使用的測試語料庫上,它實際上工作得很好,但實現高可靠性需要大量的調整。
謝謝,更新了答案 – 2011-06-20 07:59:48