繁体   English   中英

用XPath获取第二个元素文本?

[英]Get second element text with XPath?

<span class='python'>
  <a>google</a>
  <a>chrome</a>
</span>

我想获得chrome并让它像这样工作。

q = item.findall('.//span[@class="python"]//a')
t = q[1].text # first element = 0

我想将它组合成一个XPath表达式,只需要一个项而不是列表。
我试过这个,但它不起作用。

t = item.findtext('.//span[@class="python"]//a[2]') # first element = 1

实际的,而不是简化的HTML就是这样的。

<span class='python'>
  <span>
    <span>
      <img></img>
      <a>google</a>
    </span>
    <a>chrome</a>
  </span>
</span>

我试过这个,但它不起作用。

 t = item.findtext('.//span[@class="python"]//a[2]') 

这是关于//缩写的常见问题解答

.//a[2]的意思是:所有选择a属于第二当前节点的后代a他们的父母的孩子。 因此,这可能会选择多个元素或不选择任何元素 - 具体取决于具体的XML文档。

更简单地说, []运算符的优先级高于//

如果只需要返回所有节点中的一个(第二个),则必须使用括号来强制所需的优先级:

(.//a)[2]

这确实选择了第二a当前节点a后代。

对于问题中使用的实际表达式,请将其更改为

(.//span[@class="python"]//a)[2]

或将其更改为:

(.//span[@class="python"]//a)[2]/text()

我不确定问题是什么......

>>> d = """<span class='python'>
...   <a>google</a>
...   <a>chrome</a>
... </span>"""
>>> from lxml import etree
>>> d = etree.HTML(d)
>>> d.xpath('.//span[@class="python"]/a[2]/text()')
['chrome']
>>>

来自评论:

或者我发布的实际HTML的简化太简单了

你是对的。 .//span[@class="python"]//a[2]是什么意思? 这将扩展到:

self::node()
 /descendant-or-self::node()
  /child::span[attribute::class="python"]
   /descendant-or-self::node()
    /child::a[position()=2]

它将最终选择第二a孩子( fn:position()child斧头)。 因此,如果您的文档如下,则不会选择任何内容:

<span class='python'> 
  <span> 
    <span> 
      <img></img> 
      <a>google</a><!-- This is the first "a" child of its parent --> 
    </span> 
    <a>chrome</a><!-- This is also the first "a" child of its parent --> 
  </span> 
</span> 

如果您想要所有后代中的第二个,请使用:

descendant::span[@class="python"]/descendant::a[2]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM