Selenium中如何用JavaScript获取HTML Select的选项列表?
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

