Accessing specific <ul> and its <li> items with Puppeteer

I’m dealing with a webpage that lists facilities in different columns using unordered lists. Each column has a separate <ul> with various facilities represented as list items (<li>).

I need to get the second <ul> and only the fourth and fifth list items from it. When I use document.querySelector(".text-body li"), I only receive items from the first <ul>, but I’m interested in the second one instead.

All of the lists have the same class name .text-body so that’s making it tricky.

<div class="text-block hospital-facility" id="section-facilities">
  <h2 class="text-block-title"></h2>
  <div class="facility-list">
    <h4 class="text-block-list-title">Comfort During Stay</h4>
    <div class="text-body add-view-more" data-visible-item="6" data-showmore-text="More Details">
      <ul>...</ul>
    </div>
  </div>
  <div class="facility-list">
    <h4 class="text-block-list-title">Financial Services</h4>
    <div class="text-body">
      <ul>
        <li>Healthcare insurance coordination</li>
        <li>Medical travel insurance</li>
        <li>Foreign currency exchange</li>
        <li>Local ATM services</li>
        <li>Credit card transactions</li>
      </ul>
    </div>
  </div>
</div>

Here, the second <ul> has various payment methods, and I want to retrieve all of them. I know about ul:last-child, but since there are several <ul> elements, I need to figure out how to specifically select the second one.

Honestly, just use .facility-list:nth-of-type(2) ul li to grab all li’s from the second facility div. If you only want the 4th and 5th items, add [3] and [4] at the end. Works every time for me on similar scraping tasks.

To access the second <ul>, you can use document.querySelectorAll('.text-body ul')[1]. Once you have that, you can get the specific list items by chaining querySelectorAll('li') to reference the second list. Specifically, the fourth and fifth items can be accessed using querySelectorAll('li')[3] and querySelectorAll('li')[4] respectively. This way, you can accurately retrieve the required elements.

You can target the second <ul> with the nth-child selector. Try document.querySelector('.text-body:nth-child(2) ul') to grab the second text-body div and its ul element. Or if you want to be more specific about the Financial Services section, use document.querySelector('h4:contains("Financial Services") + .text-body ul') - though you might need to tweak this based on your DOM structure. Once you’ve got the right ul element, just use querySelectorAll('li') on it to get all the payment method items. I’ve found this way more reliable than indexing through all ul elements on similar pages.