如何获取倒数第二个元素?

2 投票
2 回答
760 浏览
提问于 2025-04-17 21:37

请帮我用xpath获取第二个标签的内容。下面是我写的代码,但它不管用。

import lxml.html

doc = lxml.html.document_fromstring("""
    <nav class="Paging">
            <a href="/women/dresses/cat/4?page=1" class="active">1</a>
            <a href="/women/dresses/cat/4?page=2">2</a>
            <a href="/women/dresses/cat/4?page=2" rel="next">Next »</a>
    </nav>
""")
res = doc.xpath('//nav[@class="Paging"][position() = 1]/a[position() = last() and @rel != "next"]/text()')

print(res)

2 个回答

0

你现在的表达式不管用,因为 a[position() = last() and @rel != "next"] 试图匹配最后一个元素,前提是它的 rel 属性不等于 "next"。但在你的标记中并不是这样,所以这个表达式什么都匹配不到。

你可以直接把 position()last() - 1 进行比较,这样就可以了:

res = doc.xpath('//nav[@class = "Paging" and position() = 1]'
    + '/a[position() = last() - 1]/text()')
0

你可以试试这个xpath:

//nav[@class="Paging"][position() = 1]/a[position() = last() - 1][not(@rel)]/text()

撰写回答