Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
378 views
in Technique[技术] by (71.8m points)

XPath: How to select node with some attribute by index?

I have several nodes with some particular attribute and I need to select one of them by index. For example I need to select second <div> with 'test' class - //div[@class='test'][2] doesn't work.

Is there a way to select node with some attribute by index ? How to do it?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This is a FAQ.

In XPath the [] operator has a higher precedence (binds stronger) than the // pseudo-operator.

Because of this, the expression:

//div[@class='test'][2]

selects all div elements whose class attribute is "test" and who (the div elements) are the second such div child of their parent. This is not what you want.

Use:

(//div[@class='test'])[2]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...