使用 BeautifulSoup。 使用 lxml。 不要使用正则表达式来解析HTML。
编辑 2010-01-29:这将是使用lxml的合理起点:
from lxml.html import fromstring
from lxml.html.clean import Cleaner
import requests
url = "https://dev59.com/hkvSa4cB1Zd3GeqPgKc4"
html = requests.get(url).text
doc = fromstring(html)
tags = ['h1','h2','h3','h4','h5','h6',
'div', 'span',
'img', 'area', 'map']
args = {'meta':False, 'safe_attrs_only':False, 'page_structure':False,
'scripts':True, 'style':True, 'links':True, 'remove_tags':tags}
cleaner = Cleaner(**args)
path = '/html/body'
body = doc.xpath(path)[0]
print cleaner.clean_html(body).text_content().encode('ascii', 'ignore')
你需要页面内容,因此我假设你不需要任何Javascript或CSS。此外,我也假设你只需要正文内容而不需要头部的HTML。阅读关于lxml.html.clean的介绍,看看你可以轻松清除哪些内容。比正则表达式聪明得多,是吧?
另外,要注意Unicode编码问题。你可能会遇到无法打印的HTML。
2012-11-08:从urllib2更改为使用requests。只需使用requests即可!