我是一个全新的python新手,我需要一些使用lxml查找和迭代html标记的语法方面的帮助。下面是我正在处理的用例:
HTML文件的格式相当好(但并不完美)。屏幕上有多个表,一个表包含一组搜索结果,页眉和页脚各一个。每个结果行都包含搜索结果详细信息的链接。
self.mySearchTables1.findall(".//tr")
对于self.myResultRows中的searchRow : searchLink = patentRow.findall(".//a")
它似乎没有找到链接元素。
searchLink.text
。最后,在lxml的实际API参考中,我无法找到有关find和findall调用的信息。我从我在谷歌上找到的一些代码中收集到了这些。关于如何使用lxml有效地查找和遍历HTML标记,我是不是漏掉了什么?
发布于 2009-03-02 19:27:20
好的,首先,关于解析beautifulsoup included with lxml:如果你遵循zweiterlinde和S.Lott的建议,至少使用zweiterlinde的版本。这样,您还可以从漂亮的xpath或css选择器界面中获益。
不过,我个人更喜欢伊恩·比克的HTML parser included in lxml。
其次,.find()
和.findall()
来自试图与ElementTree兼容的lxml,这两种方法在XPath Support in ElementTree中进行了描述。
这两个函数非常容易使用,但它们的XPath非常有限。我建议尝试使用完整的lxml,或者,如果您已经熟悉xpath()
method,则使用cssselect()
method。
以下是一些示例,其中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'))
发布于 2009-03-02 17:51:14
你在这个项目中不使用Beautiful Soup有什么原因吗?这将使处理不完美格式的文档变得更加容易。
https://stackoverflow.com/questions/603287
复制相似问题