You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Selenium Python在WordPress经典编辑器中添加多个H2标题

无需点击H2按钮,直接用Selenium在WordPress经典编辑器添加多个H2标题

完全可以不用点击H2按钮,直接通过send_keys添加带H2格式的内容,以下是两种更可靠的实现方式:

方法1:利用可视化编辑器的快捷键

WordPress经典编辑器的可视化模式(iframe内)支持快捷键触发标题格式:Windows/Linux用Ctrl+2,Mac用Cmd+2。切换到iframe后,通过发送快捷键+文本的方式就能批量添加H2:

from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

# 切回主页面上下文
driver.switch_to.default_content()

# 等待并切换到编辑器iframe(建议用更短的定位符,比如By.ID, 'content_ifr',经典编辑器iframe通常有这个ID)
editor_iframe = WebDriverWait(driver, 20).until(
    EC.frame_to_be_available_and_switch_to_it((By.XPATH, "/html/body/div[1]/div[2]/div[3]/div[1]/div[3]/form/div/div/div[1]/div[4]/div/div[2]/div[2]/div/div[2]/iframe"))
)

# 获取编辑器内的body元素
editor_body = driver.find_element(By.TAG_NAME, 'body')

# 添加第一个H2标题
editor_body.send_keys(Keys.CONTROL, '2')  # Mac系统替换为Keys.COMMAND
editor_body.send_keys('第一个H2标题')

# 换行后添加第二个H2标题
editor_body.send_keys(Keys.ENTER)
editor_body.send_keys(Keys.CONTROL, '2')
editor_body.send_keys('第二个H2标题')

方法2:切换到文本模式直接插入HTML代码

这种方法稳定性更高,无需依赖编辑器的可视化交互,直接切换到文本(HTML)模式,发送H2标签代码即可:

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

# 切回主页面上下文
driver.switch_to.default_content()

# 切换到文本模式(中文界面可用By.LINK_TEXT, '文本'定位按钮,避免超长XPath)
driver.find_element(By.XPATH, '//*[@id="content-tmce"]/following-sibling::a').click()

# 等待文本模式输入框加载完成
text_area = WebDriverWait(driver, 20).until(
    EC.visibility_of_element_located((By.ID, 'content'))
)

# 批量插入多个H2的HTML代码
h2_content = "<h2>第一个H2标题</h2>\n<h2>第二个H2标题</h2>\n<h2>第三个H2标题</h2>"
text_area.send_keys(h2_content)

注意事项

  • 尽量避免使用超长的绝对XPath,改用By.ID、By.CLASS_NAME或相对定位符,比如编辑器iframe常用ID为content_ifr,文本模式按钮可通过By.LINK_TEXT, '文本'定位(中文界面)。
  • 切换上下文或模式后,优先用WebDriverWait等待元素加载,减少对time.sleep的依赖,提升脚本稳定性。

内容的提问来源于stack exchange,提问作者Lubaba Ell

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 20:39:14