NodeJS使用Puppeteer解析HTML批量提取variant_id与标签文本
Got it, since you’re already using Puppeteer to grab the full page HTML, here are two solid ways to parse that <ul class="styled-radio"> structure and build your desired sizes array:
方案1:直接在Puppeteer浏览器上下文提取(推荐)
Instead of pulling the entire HTML into your Node.js environment first, you can handle the extraction directly within the browser context using page.evaluate(). This is more efficient and avoids any potential issues with HTML serialization mismatches.
Here’s the code:
const sizes = await page.evaluate(() => { // Locate the target radio list const radioList = document.querySelector('ul.styled-radio'); if (!radioList) return []; // Iterate over each list item const sizeEntries = []; const listItems = radioList.querySelectorAll('li'); listItems.forEach(item => { const radioInput = item.querySelector('input[type="radio"][name="variant_id"]'); const sizeLabel = item.querySelector('label'); // Only add valid entries where both elements exist if (radioInput && sizeLabel) { // Use the input's value directly (it's exactly the xxxxxx you need!) const variantId = radioInput.value; const sizeText = sizeLabel.textContent.trim(); sizeEntries.push(`${variantId}:${sizeText}`); } }); return sizeEntries; }); // Log the result to verify console.log(sizes); // Output: ["118018:5", "118019:6", "118020:6,5", ...]
Note: Using the input element's value attribute is far more reliable than parsing the id string—since the value is explicitly set to the variant ID you need, there’s no risk of typos or format changes breaking your extraction.
方案2:解析已获取的HTML字符串(如果必须用现有HTML变量)
If you already have the full HTML stored in your html variable and want to parse it in Node.js, you can use a library like cheerio (a lightweight jQuery-like parser).
First, install cheerio if you haven’t:
npm install cheerio
Then use this code:
const cheerio = require('cheerio'); // Load the HTML into cheerio const $ = cheerio.load(html); const sizes = []; // Traverse the list items $('ul.styled-radio li').each((_, element) => { const $item = $(element); const radioInput = $item.find('input[type="radio"][name="variant_id"]'); const sizeLabel = $item.find('label'); if (radioInput.length && sizeLabel.length) { const variantId = radioInput.attr('value'); const sizeText = sizeLabel.text().trim(); sizes.push(`${variantId}:${sizeText}`); } }); console.log(sizes); // Same desired output as above
内容的提问来源于stack exchange,提问作者James

