1

I want to get the value from an element based on the element preceding it. For example, getting the value "YYYY-MM-DD" based on the element "date"

Here is the html snippet:

enter image description here

vinayak bahri
  • 21
  • 1
  • 3

4 Answers4

2

If the value you need to extract is in the input element, you can use the following xpath;

//div[contains(text(), 'date:')]/ancestor::div[contains(@class, 'form row')]/following-sibling::input[@id=formData-rest_of_the_id_value]

Its better to use id attribute to locate web elements, because it is unique to the web element.

Check this tutorial for more on xpath

kaweesha
  • 154
  • 8
1

I used the following xpath

//div[contains(text(),'date')]/ancestor::div[contains(@class, 'form-row')]/following-sibling::div/div/div[@class='_textContainer_psmgei']

but can there be a better way?

pavelsaman
  • 4,548
  • 1
  • 13
  • 37
vinayak bahri
  • 21
  • 1
  • 3
  • You can try the following: //div[contains(text(),'date')]/ancestor::div[contains(@class, 'form-row')]/following-sibling::div//input[@type='text']::preceding-sibling::div – the_coder May 22 '20 at 12:23
1

If the element is unique then use :

//div[contains(text(), 'date:')]

If you believe that the parent element is unique and not the target element then,

You could just do:

//div[contains(@class, 'form row')]/div[contains(text(), 'date:')]

You don't have to check sibling.

Here // means anywhere in the HTML DOM, / means direct child. So the given locator finds direct child of div[contains(@class, 'form row')].

PDHide
  • 11,065
  • 2
  • 14
  • 42
0

I think input[@id=formData-rest_of_the_id_value] "rest_of_the_id_value" is auto-generated value and it will change all the time.

I prefer this way

//div[contains(text(),'date')]/ancestor::div[contains(@class,'form-row')]/following-sibling::div//div[contains(@style,'position']
ramindusn
  • 21
  • 2