使用Cheerio选择div标签下全部文本及拆分#ftext内容至变量
Got it, let's break down these two Cheerio tasks with clear examples that should cover your needs!
1. Grab all text from <div> tags
If you want to pull together all text content from every <div> on the page into a single string, this simple line does the trick:
const cheerio = require('cheerio'); // First load your HTML content into Cheerio const $ = cheerio.load(yourHtmlString); // Get merged text from all divs const allDivText = $('div').text(); console.log(allDivText);
If you need each div's text as individual entries in an array (great for processing separate blocks), use .map() instead:
const divTextsArray = $('div') .map((i, el) => $(el).text().trim()) // Trim whitespace for cleaner output .get(); // Convert Cheerio object to a plain JS array console.log(divTextsArray);
2. Split #ftext content into separate variables
This depends a bit on the structure of your #ftext element, so I'll cover the two most common scenarios:
Scenario 1: #ftext contains plain text like "A B C D"
We'll split the text, then recombine the first three parts and grab the last one:
const ftextFull = $('#ftext').text().trim(); // Split on one or more spaces (handles extra whitespace) const textParts = ftextFull.split(/\s+/); const abcString = textParts.slice(0, 3).join(' '); // "A B C" const dString = textParts[3]; // "D" console.log(abcString); console.log(dString);
Scenario 2: #ftext has structured child elements
If your HTML looks something like this:
<div id="ftext"> <span>A B C</span> <span>D</span> </div>
Just target the specific child elements directly to get their text:
// Adjust the selectors to match your actual element classes/tags const abcString = $('#ftext span:first').text().trim(); const dString = $('#ftext span:last').text().trim(); // Or if they have unique classes: // const abcString = $('#ftext .abc-group').text().trim(); // const dString = $('#ftext .d-group').text().trim();
Hope these examples work for your setup! If your #ftext has a different structure, drop a comment with the HTML snippet and I can tweak this further.
内容的提问来源于stack exchange,提问作者yk6

