如何使用Playwright+JavaScript获取下拉框选项并存入数组?
使用Playwright提取第三个下拉框的所有选项文本
问题修正
你当前的定位器存在错误:div.flex.flex-col.p-2.m-2 > div:nth-child(5) > select 中的 div:nth-child(5) 不符合页面结构,第三个下拉框所在的 <div> 是父容器的第3个子元素(前两个子元素对应第一、第二个下拉框)。
可行解决方案
以下是三种可靠的实现方式,均可正确获取第三个 <select> 的所有选项文本并存入数组:
方法1:使用Locator + allTextContents()(Playwright推荐写法)
const { chromium } = require("playwright"); const url = `你的HTML内容...`; // 保留原HTML字符串不变 (async () => { const browser = await chromium.launch({ headless: false }); const context = await browser.newContext(); const page = await context.newPage(); await page.goto(url); // 定位第三个select元素 const thirdSelect = page.locator('div.flex.flex-col.p-2.m-2 > div:nth-child(3) select'); // 获取所有option的文本内容 const optionsText = await thirdSelect.locator('option').allTextContents(); console.log("第三个下拉框选项:", optionsText); console.log("选项数量:", optionsText.length); await browser.close(); })();
方法2:使用$$eval()(原生DOM操作风格)
const { chromium } = require("playwright"); const url = `你的HTML内容...`; (async () => { const browser = await chromium.launch({ headless: false }); const context = await browser.newContext(); const page = await context.newPage(); await page.goto(url); // 直接获取第三个select下所有option的文本数组 const optionsText = await page.$$eval( 'div.flex.flex-col.p-2.m-2 > div:nth-child(3) select option', options => options.map(opt => opt.textContent.trim()) ); console.log("第三个下拉框选项:", optionsText); await browser.close(); })();
方法3:使用evaluate()(浏览器上下文执行)
const { chromium } = require("playwright"); const url = `你的HTML内容...`; (async () => { const browser = await chromium.launch({ headless: false }); const context = await browser.newContext(); const page = await context.newPage(); await page.goto(url); const optionsText = await page.evaluate(() => { // 定位第三个select元素 const thirdSelect = document.querySelector('div.flex.flex-col.p-2.m-2 > div:nth-child(3) select'); // 转换为文本数组 return Array.from(thirdSelect.options).map(opt => opt.textContent.trim()); }); console.log("第三个下拉框选项:", optionsText); await browser.close(); })();
核心说明
- 定位器修正:将原定位器中的
div:nth-child(5)替换为div:nth-child(3),匹配第三个下拉框所在的容器。 - 三种方法最终都会返回格式为
["11", "22", "33", ..., "60"]的数组,包含第三个下拉框的所有选项文本。
内容的提问来源于stack exchange,提问作者Mauro Cifuentes
相关产品推荐
相关产品推荐

