我有以下文字
testing = """
<div>
<a>11</a>
</div>
<div>
<a>21</a>
<a>23</a>
</div>
"""
我想提取<a></a>
里面的文字.下面是我的尝试,
testing = html.fromstring(testing)
testing = testing.xpath("//div")
[x.xpath("//a/text()") for x in testing]
输出是
[['11', '21', '23'], ['11', '21', '23'], ['11', '21', '23']]
但我所期待和想要的是
[['11'], ['21', '23']]
我该怎么做?
谢谢。
最佳答案
testing.xpath("//div")
返回匹配的 div
节点列表。对于每个 div
节点,您要求查找所有 a
元素,但是表达式开头的 //
将从 < em>文档树的根。您需要通过在前面加上一个点来使搜索特定于列表中的每个 div
:
[x.xpath(".//a/text()") for x in testing]
# HERE^
或者,如果适用于您的情况,您可以在一个表达式中一次性完成:
x.xpath("//div/a/text()")
关于python - 使用 lxml `.xpath()` 和 `for` 的意外输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37638500/