Van Gale..
27
好的,首先,关于解析HTML:如果你遵循zweiterlinde和S.Lott的建议,至少要使用lxml附带的beautifulsoup版本.这样你就可以获得一个漂亮的xpath或css选择器接口的好处.
但是,我个人更喜欢Ian Bicking的HTML解析器包含在lxml中.
其次,.find()和.findall()从LXML试图与ElementTree的兼容进来,并且这两种方法中所描述的XPath支持的ElementTree.
这两个函数相当容易使用,但它们的XPath非常有限.我建议尝试使用完整的lxml xpath()方法,或者,如果您已经熟悉CSS,则使用该cssselect()方法.
以下是一些示例,其中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'))