如何使用Selenium在WordPress Gutenberg编辑器中添加文章标题?
Selenium操作Gutenberg编辑器添加文章标题的正确方式
你的代码存在两个核心问题,导致无法成功输入标题:
- Gutenberg编辑器当前版本已不再使用
editor-canvasiframe,无需切换iframe上下文 - 标题输入框的定位方式错误,不能通过
<h1>标签直接定位
修正后的代码
IWebDriver driver = new FirefoxDriver(); // 导航至WordPress新建文章页面 driver.Navigate().GoToUrl("http://localhost/wordpress/wp-admin/post-new.php"); // 执行登录操作 driver.FindElement(By.Id("user_login")).SendKeys("admin"); driver.FindElement(By.Id("user_pass")).SendKeys("password"); driver.FindElement(By.Id("wp-submit")).Click(); // 等待标题输入框加载并可交互 WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10)); var titleInput = wait.Until(d => d.FindElement(By.CssSelector(".editor-post-title__input"))); // 输入文章标题 titleInput.SendKeys("Hello");
关键说明
- 移除iframe切换:Gutenberg的标题输入框位于主文档DOM中,不需要切换到iframe
- 精准定位元素:使用
.editor-post-title__input这个Gutenberg内置的类名定位标题框,比标签选择器更稳定,适配版本更新 - 优化等待逻辑:直接等待标题元素加载完成,避免无效的body等待,降低元素未找到的概率
内容的提问来源于stack exchange,提问作者smartstud
相关产品推荐
相关产品推荐

