好的,首先,关于解析 HTML:如果您遵循 zweiterlinde 和 S.Lott 的建议,至少使用以下版本lxml 中包含 beautifulsoup http://lxml.de/elementsoup.html。这样您还将获得良好的 xpath 或 css 选择器界面的好处。
不过,我个人更喜欢 Ian Bicking 的lxml 中包含 HTML 解析器 http://lxml.de/lxmlhtml.html.
第二,.find()
and .findall()
来自试图与 ElementTree 兼容的 lxml,这两种方法在ElementTree 中的 XPath 支持 http://effbot.org/zone/element-xpath.htm.
这两个函数相当容易使用,但它们是非常有限的 XPath。我建议尝试使用完整的 lxmlxpath() method http://lxml.de/xpathxslt.html#the-xpath-method或者,如果您已经熟悉 CSS,请使用cssselect() method http://lxml.de/cssselect.html.
以下是一些示例,其中 HTML 字符串的解析如下:
from lxml.html import fromstring
mySearchTree = fromstring(your_input_string)
使用 css 选择器类,您的程序大致如下所示:
# Find all 'a' elements inside 'tr' table rows with css selector
for a in mySearchTree.cssselect('tr a'):
print 'found "%s" link to href "%s"' % (a.text, a.get('href'))
使用 xpath 方法的等效方法是:
# Find all 'a' elements inside 'tr' table rows with xpath
for a in mySearchTree.xpath('.//tr/*/a'):
print 'found "%s" link to href "%s"' % (a.text, a.get('href'))