You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Puppeteer获取第二个<li>标签的文本内容?

Got it, let's get that second <li> text ("254 Beds") for you. Here's how to do it both with vanilla JavaScript and Puppeteer:

Solution to Fetch the Second <li> Element's Text

Vanilla JavaScript Fixes

Your current code grabs the first <li> because querySelector returns the first matching element. To target the second one, try either of these approaches:

  1. Use the :nth-child(2) CSS pseudo-selector
    This directly targets the second child element of the <ul>:

    const numberOfBeds = document.querySelector('.joint-list li:nth-child(2)').innerText;
    
  2. Grab all <li> elements and pick the second one
    Since JavaScript uses zero-based indexing, the second element lives at index 1:

    const allLiElements = document.querySelectorAll('.joint-list li');
    const numberOfBeds = allLiElements[1].innerText;
    

Puppeteer Implementation

Puppeteer uses async methods to interact with the page, so you'll need to use await with these approaches:

  1. Using page.$eval with the :nth-child(2) selector
    This runs the selector on the page and extracts the text in one step:

    const numberOfBeds = await page.$eval('.joint-list li:nth-child(2)', el => el.innerText);
    
  2. Using page.$$eval to collect all <li> elements
    This fetches all matching <li> elements as an array, then we access the second one:

    const numberOfBeds = await page.$$eval('.joint-list li', elements => elements[1].innerText);
    

Just make sure your Puppeteer code is wrapped in an async function, since we're using await!

内容的提问来源于stack exchange,提问作者newToDev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 10:27:45