ThinkChat🤖让你学习和工作更高效,注册即送10W Token,即刻开启你的AI之旅 广告
### 关键点:click方法是异步的,返回不代表模拟点击已经结束 JxBrowser DOM API提供的功能允许您模拟加载的网页上的任何HTML元素的单击。要模拟点击,您需要确保完全加载网页并在文档中找到所需的HTML元素: ``` DOMDocument document = browser.getDocument(); DOMElement link = document.findElement(By.tagName("button")); ``` 获得对所需HTML元素的引用后,可以使用DOMNode.click()方法模拟单击。 ``` link.click(); ``` **请注意,此方法异步工作。当此方法返回时,并不意味着单击模拟已完成。** 当您需要模拟用户操作(包括鼠标单击指定的HTML元素)时,此功能在自动测试中非常有用。 ``` import com.teamdev.jxbrowser.chromium.Browser; import com.teamdev.jxbrowser.chromium.dom.By; import com.teamdev.jxbrowser.chromium.dom.DOMDocument; import com.teamdev.jxbrowser.chromium.dom.DOMElement; import com.teamdev.jxbrowser.chromium.events.FinishLoadingEvent; import com.teamdev.jxbrowser.chromium.events.LoadAdapter; import com.teamdev.jxbrowser.chromium.swing.BrowserView; import javax.swing.*; import java.awt.*; /** * This sample demonstrates how to simulate click on a specific HTML element. */ public class DOMSimulateClickSample { public static void main(String[] args) { Browser browser = new Browser(); BrowserView browserView = new BrowserView(browser); JFrame frame = new JFrame(); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.add(browserView, BorderLayout.CENTER); frame.setSize(800, 600); frame.setLocationRelativeTo(null); frame.setVisible(true); browser.addLoadListener(new LoadAdapter() { @Override public void onFinishLoadingFrame(FinishLoadingEvent event) { if (event.isMainFrame()) { Browser browser = event.getBrowser(); DOMDocument document = browser.getDocument(); DOMElement link = document.findElement(By.tagName("button")); if (link != null) { link.click(); } } } }); browser.loadHTML("<html><body><button id='button' " + "onclick=\"alert('Button has been clicked!');\">Click Me!</button>" + "</body></html>"); } } ```