Selenium报错AttributeError: 'WebElement'无sendKeys属性如何解决
问题修复方案
场景说明
你需要操作的目标站点为 在线HTML编辑器,操作界面截图如下:
错误原因
Python 版本的 Selenium 库中,WebElement 对象的键盘输入方法为蛇形命名的 send_keys(),你代码里用的驼峰式 sendKeys() 是 Java/JS 等其他语言 Selenium 绑定的 API,因此触发属性不存在的报错。
修复代码
首先确认已导入必要依赖,再将对应两行的sendKeys替换为send_keys即可:
# 提前导入必要依赖 import time from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.chrome.options import Options # 你的原有配置(示例,保持你自己的options配置即可) options = Options() # 其余你的原有代码保持不变 w = webdriver.Chrome(executable_path='chromedriver.exe', chrome_options=options) w.get("https://onlinehtmleditor.dev/") time.sleep(4) switch_to_html ='//*[@id="ckeditor-4-output-button"]' paste_code = '//*[@id="ckeditor-4-output"]/div/div[6]/div[1]/div/div' element = w.find_element_by_xpath(switch_to_html).click() time.sleep(2) # element = w.find_element_by_xpath(paste_code).send_keys("Hi") clickElement = w.find_element_by_css_selector(".CodeMirror-lines") time.sleep(1) clickElement.click() # 仅替换方法名即可 clickElement.send_keys(Keys.CONTROL + "a") clickElement.send_keys(Keys.DELETE)
可选优化方案
针对CodeMirror这类富文本编辑区域,直接操作元素偶尔会出现焦点丢失、输入不生效的问题,可改用ActionChains实现更稳定的连续键鼠操作:
# 新增导入ActionChains from selenium.webdriver.common.action_chains import ActionChains # 原有定位到clickElement之后的代码替换为以下内容 actions = ActionChains(w) actions.move_to_element(clickElement)\ .click()\ .key_down(Keys.CONTROL)\ .send_keys('a')\ .key_up(Keys.CONTROL)\ .send_keys(Keys.DELETE)\ .perform()
内容的提问来源于stack exchange,提问作者Sainita
相关产品推荐
相关产品推荐

