Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XPath to select 1 element if one of two exists

I want to select one element if one out of 2 exist while using this for 2 pages

1st page (price with discount)

<div class="price">
  <span class="originalRetailPrice">$2,990.00</span>
  </div>
</div>
<div class="price">
      <span class="salePrice">$1,794.00</span>
</div>

or 2nd page (only one price)

<div class="price">
  $298.00
</div>

I have used //span[@class="originalRetailPrice"] | (//div[@class="priceBlock"])[1] but I get the price twice

What I want is to select the first price when it's class="originalRetailPrice" or when it's //div[@class="price"]/text()[1]

So finally I want to make the selection to work on both pages

like image 237
Amr Ali Avatar asked Jun 01 '15 08:06

Amr Ali


People also ask

How do you handle multiple elements with the same XPath?

If an xpath refers multiple elements on the DOM, It should be surrounded by brackets first () and then use numbering. if the xpath refers 4 elements in DOM and you need 3rd element then working xpath is (common xpath)[3].

How do you select the second element with the same XPath?

For example if both text fields have //input[@id='something'] then you can edit the first field xpath as (//input[@id='something'])[1] and the second field's xpath as (//input[@id='something'])[2] in object repository.

What is the meaning of '/' in XPath?

0 votes. Single Slash “/” – Single slash is used to create Xpath with absolute path i.e. the xpath would be created to start selection from the document node/start node.


1 Answers

Use // to get texts at any level inside <div class="price">:

//div[@class="price"][1]//text()

Result:

Text=''
Text='$2,990.00'
Text=''

And filter the empty texts with: text()[normalize-space() and not(ancestor::a | ancestor::script | ancestor::style)]

//div[@class="price"][1]//text()[normalize-space() and not(ancestor::a | ancestor::script | ancestor::style)]

Result 1st page:

Text='$2,990.00'

Result 2nd page:

Text='$298.00'
like image 168
Stéphane Bruckert Avatar answered Oct 05 '22 14:10

Stéphane Bruckert