sipher_z
sipher_z

Reputation: 1251

Cannot find correct element with same class name

I have the following HTML snippet:

<div id="result-1">
  <div class="page">
    <div class="collapsingblock">
      <h4>Click Me</h4>
    </div>
    <div class="collapsingblock collapsed">
      <h4>No, Click Me</h4>
    </div>
  </div>
</div>

What I'm trying to do, is to find the second collapsingblock and it's h4

I have the following:

(//div[@id="result-1"]/div[@class="page"]/div[@class="collapsingblock"])[2]/h4

My xPath doesn't return the element. If I replace it with [1] it finds the first instance of collapsingblock though

Any ideas?

Thanks

UPDATE:

I have just noticed, that the HTML is using JavaScript to add/remove an additional class to the second collapsingblock, which collapsed

Upvotes: 0

Views: 62

Answers (2)

Mathias M&#252;ller
Mathias M&#252;ller

Reputation: 22617

The problem is that the value of the class attribute of the second inner div element is not equal to "collapsingblock", as you can see:

<div class="collapsingblock collapsed">
  <h4>No, Click Me</h4>
</div>

Even though class has very clear-cut semantics in HTML, it does not mean anything special to XPath, it's an attribute like any other.

Use contains() to avoid this problem:

(//div[@id="result-1"]/div[@class="page"]/div[contains(@class,"collapsingblock")])[2]/h4

Then, the only result of the expression above is

<h4>No, Click Me</h4>

By the way, parentheses around the lefthand part of the expression are not necessary in this case:

//div[@id="result-1"]/div[@class="page"]/div[contains(@class,"collapsingblock")][2]/h4

will do exactly the same, given this particular input document.

Upvotes: 1

flafoux
flafoux

Reputation: 2110

the parenthesis is necessary because of priority :

(//div[@id="result-1"]/div[@class="page"]/div[@class="collapsingblock"])[2]/h4

Upvotes: 0

Related Questions