Home > Blockchain >  Extract all <li> elements from tag with certain class name
Extract all <li> elements from tag with certain class name

Time:10-06

Probably the title of my question seems to be ambiguous, since I am not familiar with glossary of html terms. Suppose I want to find a tag, with particular attribute name. In my case I am looking for tag that contains data-scroll-id with particular name that contains "requirements":

data-scroll-id="requirements-1"
data-scroll-id="requirements-expected"
data-scroll-id="requirements-main-2"

For this purpose I use following xpath construction (it works):
//*[contains(@data-scroll-id, 'requirements')]
The problem is that I want to extract <li> elements of particular tags as a separate elements/list of element (As on image below). Each <li> tag contain specific information I want to extract. I cannot access to this <li> tags using class name since from page to page their class name my differ, so I need to find parent element with constant class name for instance. In my case I chose data-scroll-id="requirements-1" (As on image below). Moreover, the number of tags inside my "main" tags may differ to from 1 to N.

Question: How can I extract child <li> tags knowing attribute name of parent tag (as on image below).

image

CodePudding user response:

Use JQuery

quotes = []; 
$('div[data-scroll-id="requirements-1"]').each(function() {
    var quote = {
      'li': $(this).find('li[class="OfferView1ehZBj"]').text(), 
    }
    quotes.push(quote);
    console.log(quote);
});

CodePudding user response:

To find all li elements anywhere within a div having data-scroll-id of requirements-1 use:

//div[@data-scroll-id="requirements-1"]//li

If it is not always a div or the value is not always exactly "requirements-1", then you can use a predicate similar to your original example to locate li elements anywhere within an element having attribute data-scroll-id containing text requirements:

//*[contains(@data-scroll-id,"requirements")]//li

Or if the value is always "requirements-1":

//*[@data-scroll-id = "requirements-1"]//li
  • Related