python - 有没有办法在 Python 中为 lxml 指定固定(或可变)数量的元素

标签 python html lxml screen-scraping

一定有更简单的方法来做到这一点。我需要大量 html 文档中的一些文本。在我的测试中,找到它的最可靠方法是在 div 元素的 text_content 中查找特定单词。如果我想检查包含我的文本的元素上方的特定元素,我一直在枚举我的 div 元素列表并使用包含我的文本的元素的索引,然后通过对索引进行操作来指定前一个元素。但我相信一定有更好的方法。我似乎无法弄清楚。

如果不清楚

for pair in enumerate(list_of_elements):
    if 'the string' in pair[1].text_content():
        thelocation=pair[0]

the_other_text=list_of_elements[thelocation-9].text_content()     

theitem.getprevious().getprevious().getprevious().getprevious().getprevious().getprevious().getprevious().getprevious().getprevious().text_content()

最佳答案

lxml支持XPath :

from lxml import etree
root = etree.fromstring("...your xml...")

el, = root.xpath("//div[text() = 'the string']/preceding-sibling::*[9]")

关于python - 有没有办法在 Python 中为 lxml 指定固定(或可变)数量的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2367000/

相关文章:

python - 如何有条件地分隔单元格值并使用 Pandas 添加到列

html - Colspan 不适用于 <td> 宽度设置? (IE7)

javascript - 从选择列表中删除项目 (Internet Explorer 10)

python - lxml etree 获取元素之前的所有文本

python - 如何调试 Web2py 应用程序?

python - 转换 pandas 数据框中的 tf-idf 矩阵

python - 单例生成器,多个消费者

html - 摆脱这个边距和垂直高度和对齐方式

python - 如何使用 lxml 和 XPATH 在单个查询中检索所有子节点

python - 使用 lxml 解析 HTML - 如何在结果列表中保留空内容?