如何使用Node.js版Selenium抓取图片所示的按钮点击文本
Hey there! Let's break down why your current XPath isn't working and get you set up with a working solution.
The Problem With Your Current XPath
Your code //*[@class='']//*[text()=''] has empty values for both the class attribute and the text match. Browsers can't find any elements that match this—after all, the button you're targeting definitely has a visible text label and likely a non-empty class attribute assigned to it.
Step-by-Step Fix to Grab the Button Text
Here's how to craft a precise XPath to capture that button's text:
Inspect the Button Element
Open your browser's DevTools (press F12), then use the element picker tool to select the button you want to scrape. This will show you the button's HTML structure, including its class, tag name, and text content.Use Specific Attributes or Text for Targeting
Depending on what you see in the inspector, use one of these approaches:- Match by exact class and tag: If the button has a class like
action-btnand is a<button>tag, use://button[@class='action-btn']/text() - Match by exact text: If the button's text is something like "Submit Form", use:
//*[text()='Submit Form']/text() - Handle multi-class attributes: If the button has multiple classes (e.g.,
btn btn-success), usecontains()to match part of the class://button[contains(@class, 'btn-success')]/text() - Clean up whitespace: If the button text has extra spaces or line breaks, use
normalize-space()to ignore them://button[normalize-space(text())='Submit Form']/text()
- Match by exact class and tag: If the button has a class like
Test Your XPath
In DevTools' "Console" tab, you can test your XPath with$x("your-xpath-here")to make sure it returns the correct button element before using it in your scraping code.
Example Scenario
If the button in your image has the text "Login" and a class of primary-login-btn, your working XPath would look like this:
//button[@class='primary-login-btn']/text()
Give this a try, and you should be able to grab that button text successfully!
内容的提问来源于stack exchange,提问作者Sunil kumar

