python - 需要python lxml语法帮助来解析html

标签 python html-parsing lxml

我是 python 的新手,我需要一些有关使用 lxml 查找和迭代 html 标签的语法方面的帮助。以下是我正在处理的用例:

HTML 文件格式良好(但并不完美)。屏幕上有多个表格,一个包含一组搜索结果,一个用于页眉和页脚。每个结果行都包含一个搜索结果详细信息的链接。

  1. 我需要找到带有搜索结果行的中间表(这个我能弄清楚):

        self.mySearchTables = self.mySearchTree.findall(".//table")
        self.myResultRows = self.mySearchTables[1].findall(".//tr")
    
  2. 我需要找到此表中包含的链接(这是我卡住的地方):

        for searchRow in self.myResultRows:
            searchLink = patentRow.findall(".//a")
    

    它似乎并没有真正找到链接元素。

  3. 我需要链接的纯文本。我想如果我实际上首先获得了链接元素,它会类似于 searchLink.text

最后,在 lxml 的实际 API 引用中,我无法找到有关 find 和 findall 调用的信息。我从在谷歌上找到的一些代码中收集到了这些。我是否遗漏了有关如何使用 lxml 有效查找和迭代 HTML 标记的内容?

最佳答案

好的,首先,关于解析 HTML:如果你遵循 zweiterlinde 和 S.Lott 的建议,至少使用 beautifulsoup included with lxml 的版本。 .这样,您还将受益于一个不错的 xpath 或 css 选择器界面。

不过,我个人更喜欢 Ian Bicking 的 HTML parser included in lxml .

其次,.find().findall()来自lxml试图兼容ElementTree,这两种方法在XPath Support in ElementTree中有描述.

这两个函数相当容易使用,但它们的 XPath 非常有限。我建议尝试使用完整的 lxml xpath() method或者,如果您已经熟悉 CSS,请使用 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'))

关于python - 需要python lxml语法帮助来解析html,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/603287/

相关文章:

python - 使用 lxml 在 xml 中进行复杂搜索

python - 从简单的 pandas 数据帧创建矩阵

c# - 使用 HTML Agility Pack 抓取元标签和评论

html - 如何从shell脚本中的html表中提取数据?

c# - 如何像 c# 中的 html 解析器一样解析 asp.net mvc razor view (cshtml)

xpath - 从分布在不同 div 的列表中提取内容

Python/lxml : Nested for loops

python - argparse 一个参数而不是其他几个参数

python - 显示 3D 表面网格的快速简单方法

python - 在 Google App Engine (GAE) 上运行 Boto