如何使用Selenium WebDriver正确点击id为send-button的div元素?
Let's work through this together to get your click working correctly. First, let's break down the issues in your current code:
- Syntax Error: Your synchronous code has a missing closing quote in
By.id("send-button))— it should beBy.id("send-button"). - Wrong Element Type: You're using an XPath targeting an
<a>tag, but the actual element is a<div>, so that XPath will never find the right element. - No Wait Logic: Directly calling
.click()without waiting for the element to be ready can lead to errors likeElementNotInteractableExceptionorNoSuchElementExceptionif the page loads asynchronously.
Correct Synchronous Code (Java Example)
We'll use explicit waits to ensure the element is clickable before interacting with it, and fix the id selector:
// Import required wait classes first import org.openqa.selenium.support.ui.WebDriverWait; import org.openqa.selenium.support.ui.ExpectedConditions; import java.time.Duration; // Wait up to 10 seconds for the send-button to be clickable WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10)); wait.until(ExpectedConditions.elementToBeClickable(By.id("send-button"))).click();
Correct Asynchronous Code (JavaScript Example)
We'll replace the incorrect XPath with the id selector, add proper wait logic, and clean up the reload wait (which isn't the right condition here):
const { Builder, By, Key, until } = require('selenium-webdriver'); (async function example() { let driver = await new Builder().forBrowser('firefox').build(); try { await driver.get('https://onyolo.com/VFUF5VtxPJ'); // Input your test text await driver.findElement(By.name('text')).sendKeys('test', Key.RETURN); // Wait for the send-button to be clickable (10 second timeout) await driver.wait(until.elementToBeClickable(By.id('send-button')), 10000); // Click the button await driver.findElement(By.id('send-button')).click(); // Add any post-click waits here if needed (e.g., wait for a confirmation message) } finally { await driver.quit(); } })();
Key Notes:
- Use ID Selectors:
By.id()is the most reliable and fastest way to locate elements since IDs are meant to be unique on a page. - Always Wait: Explicit waits (
until.elementToBeClickable) are far better than implicit waits or hardcoded sleeps — they ensure you only interact with elements when they're ready. - Avoid Unnecessary XPaths: Unless you have no other option, stick to simple selectors (id, name, class) over complex XPaths to keep your code maintainable.
内容的提问来源于stack exchange,提问作者Azrupt Clan
相关产品推荐
相关产品推荐

