如何使用Selenium C#向Discord频道文本框输入内容
Discord消息框Selenium定位与输入问题解决方案
问题描述
尝试用Selenium C#向Discord频道的消息框输入内容时,无法正确定位WebElement(怀疑XPath存在问题)。手动登录跳转至与小号的频道后,使用SendKeys方法出现OpenQA.Selenium.ElementNotInteractableException: 'element not interactable'错误,改用JavaScript执行脚本仍未解决问题。
当前代码
using OpenQA.Selenium; using OpenQA.Selenium.Chrome; using OpenQA.Selenium.DevTools.V108.IndexedDB; using OpenQA.Selenium.Interactions; using OpenQA.Selenium.Support.UI; using SeleniumExtras.WaitHelpers; namespace discord { internal class Program { static void Main(string[] args) { IWebDriver driver = new ChromeDriver(); driver.Navigate().GoToUrl("https://discord.com/channels/@me"); Thread.Sleep(40000); driver.Navigate().GoToUrl("https://discord.com/channels/@me/1036205803130077195"); Actions actions = new Actions(driver); Thread.Sleep(10000); By textBoxLocator = By.XPath("//*[@id=\"app-mount\"]/div[2]/div[1]/div[1]/div/div[2]/div/div/div/div/div[3]/div[2]/main/form/div/div[1]/div/div[3]"); string message = "Discord test20"; WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10)); IWebElement textBox = wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementToBeClickable(textBoxLocator)); ((IJavaScriptExecutor)driver).ExecuteScript($"arguments[0].value = '{message}';", textBox); ((IJavaScriptExecutor)driver).ExecuteScript("var event = new Event('keydown'); event.key = 'Enter'; arguments[0].dispatchEvent(event);", textBox); } } }
旧代码
using OpenQA.Selenium; using OpenQA.Selenium.Chrome; using OpenQA.Selenium.DevTools.V108.IndexedDB; using OpenQA.Selenium.Interactions; using OpenQA.Selenium.Support.UI; using SeleniumExtras.WaitHelpers; namespace discord { internal class Program { static void Main(string[] args) { IWebDriver driver = new ChromeDriver(); driver.Navigate().GoToUrl("https://discord.com/channels/@me"); Thread.Sleep(40000); driver.Navigate().GoToUrl("https://discord.com/channels/@me/1036205803130077195"); Actions actions = new Actions(driver); Thread.Sleep(10000); By textBoxLocator = By.XPath("//*[@id=\"app-mount\"]/div[2]/div[1]/div[1]/div/div[2]/div/div/div/div/div[3]/div[2]/main/form/div/div[1]/div/div[3]"); WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10)); IWebElement textBox = wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementToBeClickable(textBoxLocator)); actions.MoveToElement(textBox).Click().Perform(); textBox.SendKeys("test 15"); actions.SendKeys(Keys.Enter); } } }
消息框HTML结构
空消息框状态
<div class="textArea-2CLwUE textAreaSlate-9-y-k2 slateContainer-3x9zil"> <div> <div class="placeholder-1rCBhr slateTextArea-27tjG0 fontSize16Padding-XoMpjI" aria-hidden="true">Message @Lex<3</div> <div role="textbox" spellcheck="true" aria-haspopup="listbox" aria-invalid="false" aria-autocomplete="list" class="markup-eYLPri editor-H2NA06 slateTextArea-27tjG0 fontSize16Padding-XoMpjI" autocorrect="off" data-can-focus="true" aria-label="Message @Lex <3" aria-multiline="true" data-slate-editor="true" data-slate-node="value" contenteditable="true" zindex="-1" style="position: relative; outline: none; white-space: pre-wrap; overflow-wrap: break-word; --darkreader-inline-outline: initial;" data-darkreader-inline-outline=""> <div data-slate-node="element"> <span data-slate-node="text"> <span data-slate-leaf="true" class="emptyText-1o0WH_"> <span data-slate-zero-width="n" data-slate-length="0"> <br> </span> </span> </span> </div> </div> </div> </div>
输入内容后状态
<div class="textArea-2CLwUE textAreaSlate-9-y-k2 slateContainer-3x9zil"> <div> <div role="textbox" spellcheck="false" aria-haspopup="listbox" aria-invalid="false" aria-autocomplete="list" class="markup-eYLPri editor-H2NA06 slateTextArea-27tjG0 fontSize16Padding-XoMpjI" autocorrect="off" data-can-focus="true" aria-label="Message @Lex <3" aria-multiline="true" data-slate-editor="true" data-slate-node="value" contenteditable="true" zindex="-1" style="position: relative; outline: none; white-space: pre-wrap; overflow-wrap: break-word; --darkreader-inline-outline: initial;" data-darkreader-inline-outline=""> <div data-slate-node="element"> <span data-slate-node="text"> <span data-slate-leaf="true" class=""> <span data-slate-string="true">I wish you a happy day</span> </span> </span> <br> </div> </div> </div> </div>
解决方案
1. 替换稳定的元素定位方式
你使用的绝对XPath极易因Discord页面结构更新失效,改用基于属性的定位:
- CSS选择器(推荐):
By textBoxLocator = By.CssSelector("[role='textbox'][contenteditable='true'][data-slate-editor='true']");
- XPath替代方案:
By textBoxLocator = By.XPath("//div[@role='textbox' and @contenteditable='true' and @data-slate-editor='true']");
2. 正确输入并发送消息
Discord消息框基于Slate编辑器,直接操作value属性无效,推荐两种有效方式:
方式一:模拟真实用户输入
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(15)); IWebElement textBox = wait.Until(ExpectedConditions.ElementToBeClickable(textBoxLocator)); // 激活输入框 textBox.Click(); // 清空原有内容(可选) textBox.SendKeys(Keys.Control + "a"); textBox.SendKeys(Keys.Delete); // 输入消息 textBox.SendKeys("Discord test20"); // 发送消息 textBox.SendKeys(Keys.Enter);
方式二:JavaScript插入文本(适配Slate编辑器)
IWebElement textBox = wait.Until(ExpectedConditions.ElementIsVisible(textBoxLocator)); string message = "Discord test20"; // 通过JS修改编辑器内容并触发输入事件 ((IJavaScriptExecutor)driver).ExecuteScript(@" const editor = arguments[0]; const text = arguments[1]; let textNode = editor.querySelector('[data-slate-string]'); if (textNode) { textNode.textContent = text; } else { const span = document.createElement('span'); span.setAttribute('data-slate-string', 'true'); span.textContent = text; const leafSpan = editor.querySelector('[data-slate-leaf]'); leafSpan.innerHTML = ''; leafSpan.appendChild(span); } editor.dispatchEvent(new Event('input', { bubbles: true })); ", textBox, message); // 发送消息 textBox.SendKeys(Keys.Enter);
3. 优化等待逻辑
移除不稳定的Thread.Sleep(),改用显式等待:
// 等待页面加载完成 wait.Until(driver => ((IJavaScriptExecutor)driver).ExecuteScript("return document.readyState").Equals("complete")); // 等待消息框可见 wait.Until(ExpectedConditions.ElementIsVisible(textBoxLocator));
完整修正代码
using OpenQA.Selenium; using OpenQA.Selenium.Chrome; using OpenQA.Selenium.Support.UI; using SeleniumExtras.WaitHelpers; using System; namespace discord { internal class Program { static void Main(string[] args) { IWebDriver driver = new ChromeDriver(); driver.Manage().Window.Maximize(); WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(20)); try { driver.Navigate().GoToUrl("https://discord.com/channels/@me"); // 等待手动登录完成(可替换为自动登录逻辑) wait.Until(driver => driver.Url.Contains("@me")); driver.Navigate().GoToUrl("https://discord.com/channels/@me/1036205803130077195"); // 等待页面加载完成 wait.Until(d => ((IJavaScriptExecutor)d).ExecuteScript("return document.readyState").Equals("complete")); // 定位消息框 By textBoxLocator = By.CssSelector("[role='textbox'][contenteditable='true'][data-slate-editor='true']"); IWebElement textBox = wait.Until(ExpectedConditions.ElementToBeClickable(textBoxLocator)); // 激活并发送消息 textBox.Click(); textBox.SendKeys("Discord test20"); textBox.SendKeys(Keys.Enter); } catch (Exception ex) { Console.WriteLine($"错误:{ex.Message}"); } finally { // 可选:关闭浏览器 // driver.Quit(); } } } }
内容的提问来源于stack exchange,提问作者Lexi
相关产品推荐
相关产品推荐

