如何使用Selenium Python向非input元素写入文本(Google Chat场景)
解决Google Chat自动化发送消息(contenteditable文本框)的问题
这个文本框是带contenteditable="true"属性的div,不是标准的标签,直接用send_keys经常会失效,试试下面几种方案:
方案1:先激活元素再发送文本
先点击激活输入框,再执行send_keys,能解决因未激活导致的输入失败问题:
from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC # 等待元素可点击并点击激活 input_box = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.ID, "T2Ybvb0"))) input_box.click() # 清空原有内容(可选,根据需要执行) input_box.clear() # 发送消息 input_box.send_keys("GOOD MORNING")
方案2:用JavaScript直接设置内容
对于contenteditable元素,用JS直接修改内容往往更可靠:
input_box = WebDriverWait(driver, 20).until(EC.presence_of_element_located((By.ID, "T2Ybvb0"))) # 用innerHTML设置内容(支持HTML格式) driver.execute_script("arguments[0].innerHTML = 'GOOD MORNING';", input_box) # 或者用textContent设置纯文本内容 # driver.execute_script("arguments[0].textContent = 'GOOD MORNING';", input_box)
方案3:设置内容后触发输入事件
有些网站需要检测input事件才会识别输入内容,设置完后手动触发事件:
input_box = WebDriverWait(driver, 20).until(EC.presence_of_element_located((By.ID, "T2Ybvb0"))) driver.execute_script(""" arguments[0].innerHTML = 'GOOD MORNING'; // 触发input事件让页面识别内容变化 const inputEvent = new Event('input', { bubbles: true }); arguments[0].dispatchEvent(inputEvent); """, input_box)
额外提示
Google Chat的元素ID(比如T2Ybvb0)可能是动态生成的,刷新后会改变,建议用更稳定的定位方式,比如结合role和contenteditable属性:
input_box = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//div[@role='textbox' and @contenteditable='true']")))
内容的提问来源于stack exchange,提问作者Mike Johnes
相关产品推荐
相关产品推荐

