1
<div>
    <pre>
        <span class="attr">id:</span>
        <span class="text">1</span>
        <span class="attr">time:</span>
        <span class="text">42</span>
        <span class="attr">length:</span>
        <span class="text">74</span>

        <span class="attr">id:</span>
        <span class="text">2</span>
        <span class="attr">time:</span>
        <span class="text">57</span>
        <span class="attr">length:</span>
        <span class="text">74</span>
    </pre>
</div>

Here's a mockup of some HTML I'm working with. I'm trying to use XPATH to find the amount of time that is associated with id: 1, and only id: 1, not id: 2.

//span[@class = 'attr'][text()='id:']/following-sibling::span[1][text()='1']

correctly gets the '1' element for id for me, but my attempt to do

 //span[@class = 'attr'][text()='id:']/following-sibling::span[1][text()='1']/following-sibling::span[1][text()='time:']/following-sibling::span[1]

in order to grab the number after time after id: 1 doesn't work for me. I need the xpath to identify only the times after a certain id, so using a single following id after the time element won't work for me, as it also needs to find the id. Is it even possible to do following-sibling twice/thrice in a row? Is there a better way to do this?

kjhughes
  • 106,133
  • 27
  • 181
  • 240
Keenan
  • 79
  • 9
  • 2
    Sure, you can use `following-sibling::` multiple times. I've tested your XPaths, and both work. What do you mean by "won't work for me"? – kjhughes Mar 22 '17 at 21:50
  • Sorry, looks like that is indeed the case. On my real code was just confusing what number I should put after the last span. Thanks anyways :) – Keenan Mar 23 '17 at 13:36

1 Answers1

1

Yes, you can use the following-sibling:: axis multiple times.

Your XPath works as intended. Given the layout of your HTML, there's not much you can do by way of shortening the XPath other than to perhaps use the string value of the spans rather than child text() nodes:

 //span[@class='attr'][.='id:']/following-sibling::span[1][.='1']
                               /following-sibling::span[1][.='time:']
                               /following-sibling::span[1]
kjhughes
  • 106,133
  • 27
  • 181
  • 240
  • Is there a difference between using [text()='1'] and [.='1'] other than the second being easier to write? Thanks – Keenan Mar 23 '17 at 14:02
  • Yes, most definitely they are different in general, but in your case it won't matter. To understand the differences, see [**XPath text() = is different than XPath . =**](http://stackoverflow.com/q/34593753/290085) – kjhughes Mar 23 '17 at 14:06