Puppeteer按值选择按钮元素失败,如何正确定位?
Hey there! Let's break down why your code isn't finding that button and fix it up.
The Root Problem
Your button HTML is <button> MyList </button> — notice there's no value attribute here. The selector button[value="MyList"] looks for buttons that have a value property set to "MyList" (like <input type="button" value="MyList">), but your button's "MyList" is just inner text, not a value attribute. That's why Puppeteer can't locate it!
Correct Ways to Select Your Button
Here are a few reliable methods to target that button:
Use Puppeteer's
:has-text()pseudo-class (simple and straightforward for text matching):// Click the button with exact text match await page.click('button:has-text("MyList")'); // If there are extra spaces around the text, use a partial match await page.click('button:*:has-text("MyList")');Use XPath for precise text matching (great if you need more control over text content):
// Exact text match (works if there's no extra whitespace) await page.click('//button[text()="MyList"]'); // Partial match (handles extra spaces or partial text) await page.click('//button[contains(text(), "MyList")]');Add an ID/class to your button for more stable selection (best practice for test reliability, since text can change):
Update your HTML first:<button id="my-list-button"> MyList </button>Then select it with the ID in Puppeteer:
await page.click('#my-list-button');
A Quick Note on page.type()
You tried using await page.type(...) on the button, but page.type() is meant for input fields where you can type text. Buttons don't accept text input, so you can skip that line entirely and just use page.click() to trigger the button.
内容的提问来源于stack exchange,提问作者MadCatm2

