HotTeaLover
HotTeaLover

Reputation: 93

XPath: how to select elements that are related to other on the same level

The question is simple but I don't have enough practice for this case :)

How to get price text value from every div within "block" if we know that we need only item_promo elements.

<div class="block">
     <div class="item_promo">item</div>
     <div class="item_price">123</div>
</div>
<div class="block">
     <div class="item_promo">item</div>
     <div class="item_price">456</div>
</div>
<div class="block">
     <div class="item_promo">item</div>
     <div class="item_price">789</div>
</div>
<div class="block">
     <div class="item">item</div>
     <div class="item_price">222</div>
</div>
<div class="block">
     <div class="item">item</div>
     <div class="item_price">333</div>
</div>

Upvotes: 2

Views: 12182

Answers (2)

kjhughes
kjhughes

Reputation: 111726

This XPath,

//div[div/@class='item_promo']/div[@class='item_price']

will return those item_price class div elements with sibling item_promo class div elements:

<div class="item_price">123</div>
<div class="item_price">456</div>
<div class="item_price">789</div>

This will work regardless of label/price order.

Upvotes: 3

SomeDude
SomeDude

Reputation: 14238

You could use the xpath :

//div[@class='block']/*[@class='item_promo']/following-sibling::div[@class='item_price']/text()

You look for div elements that has attribute class with value item_promo and look at its following sibling which has an attribute item_price and grab the text.

Upvotes: 6

Related Questions