如何使用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:
<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:
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;Grab all
<li>elements and pick the second one
Since JavaScript uses zero-based indexing, the second element lives at index1: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:
Using
page.$evalwith 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);Using
page.$$evalto 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

