Home > Net >  extracting attribute value of parent element using Selenium
extracting attribute value of parent element using Selenium

Time:11-10

Experienced with Java, pretty new to Selenium, locators, etc.

Buried deep in some HTML is several similar divisions:

<div tabgroup="topTabs__County Summary" sectiongroup class="field TextDescription tab">
  <label for="request_48543">
    <span class="label">Monument</span>
  </label>
</div>
<div tabgroup="topTabs__County Summary" sectiongroup class="field DropDownList readonly tab">
  <label for="request_48543">
    <span class="label">Geolocation</span>
  </label>
</div>
<div tabgroup="topTabs__County Summary" sectiongroup class="field SingleLineText tab">
  <label for="request_48543">
    <span class="label">Intersection</span>
  </label>
</div

I need some Selenium magic to find a label with a specific value then backtrack to find that label's division and from that division extract the value of a given attribute. Drilling down seems fairly easy but how does one "back up" ?

For example, given "Geolocation" I'd like to extract "field DropDownList readonly tab"

I've tried things like

WebElement chill = m.findElement(By.xpath("../..//span[text='Geolocation']"));

to no avail

CodePudding user response:

You reversed the order of going to the parent element, and you need () in text. The xpath should be

"//span[text()='Geolocation']/../.."

Another option is to look for an element that has a chilled with "Geolocation" text

"//div[.//span[text()='Geolocation']]"

this might give you more results, depends on the html structure that is not in the question. In that case you can add unique attribute, for example tabgroup

"//div[.//span[text()='Geolocation']][@tabgroup]"

this will return only <div> tag that has tabgroup attribute.

To extract the data use getAttribute("class") on chill WebElement

  • Related