Rich Stevens Rich Stevens - 1 year ago 49
HTML Question

How do I grab contents of a div only if the class in the div above has certain text in it

<li class="amenities__item amenities__item--yes">
<div class="amenities__icon amenities__icon--yes"></div>
<div class="amenities__label">
Parking
</div>
</li>


I want to grab the text "Parking" but ONLY if the div before it has the word "yes" in it.

I have been trying variations of:

//div[contains(class/following-sibling::text(), 'Yes')]


But seems I need this to be more specific somehow.

Answer Source

This XPath,

normalize-space(//div[contains(preceding-sibling::div[1]/@class, 'yes')])

will return the space-normalized string value of the div with an immediately preceding sibling div with yes in its @class attribute value. For your posted example HTML, that will be:

Parking

If you instead wish to test that the string value of the preceding div equal Yes, then use this XPath:

normalize-space(//div[preceding-sibling::div[1] = 'Yes'])

Update to address comment question about how to deal with multiple such div elements

For the first XPath, you can select a nodeset (XPath 1.0) or a sequence (XPath 2.0+) of such div elements:

//div[contains(preceding-sibling::div[1]/@class, 'yes')]

The way you'd iterate over the resulting nodeset/sequence would depend upon the language hosting the XPath library. Within XPath, should you know that you want, say, the 2nd such div, you can append [2]:

//div[contains(preceding-sibling::div[1]/@class, 'yes')][2]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download