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

Selenium中如何用JavaScript获取HTML Select的选项列表?

How to Traverse Dropdown Options in JavaScript Selenium

Got it, let's sort this out for JavaScript Selenium! While C#, Python, and Java have straightforward built-in methods to grab dropdown options, JS does too—you just need to leverage the Select class from the Selenium webdriver module. Here's how to do it cleanly:

Using the Selenium Select Class

First, make sure you're importing the Select class (if you're working in a Node.js environment):

const { Select } = require('selenium-webdriver');

Then, initialize a Select object for your dropdown element:

const quantityDropdown = new Select(driver.findElement({css: '.quantity'}));

Now you can easily get all the options and traverse them:

// Get all option elements from the dropdown
const options = await quantityDropdown.getOptions();

// Traverse each option to extract text and value
for (const option of options) {
  const optionText = await option.getText();
  const optionValue = await option.getAttribute('value');
  console.log(`Option: "${optionText}" | Value: "${optionValue}"`);
}

Alternative: Directly Locate Option Elements

If you prefer not to use the Select class, you can directly target all <option> children of your dropdown:

// Find all option elements inside the .quantity dropdown
const options = await driver.findElements({css: '.quantity option'});

// Loop through each option
for (const option of options) {
  const text = await option.getText();
  const value = await option.getAttribute('value');
  // Do whatever you need with text/value here
}

Why innerHTML Isn't Ideal

The innerHTML method returns a raw string of all the dropdown's inner HTML, which includes all the markup and whitespace—hence the messy text block you're seeing. By targeting the <option> elements directly, you can extract clean, structured text and values without parsing through cluttered HTML.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 08:18:13