Python3.7.4环境下Chromedriver+Selenium无法输入‘s’键问题求助
解决Selenium send_keys无法输入's'字符的问题
我之前也碰到过这种离谱的单个字符输入失败的情况!结合你的环境(Python 3.7.4 + Selenium 3.141.0 + Chrome/Chromedriver 77/78),给你几个经过验证的解决方案:
用ActionChains逐个字符模拟输入
有时候批量调用send_keys会触发浏览器或页面的隐性字符过滤,换成逐个发送字符就能绕过这个问题。代码示例:from selenium.webdriver.common.action_chains import ActionChains password_input = form_element.find_element_by_xpath(password_xpath) target_password = "password" # 初始化动作链 action = ActionChains(driver) action.click(password_input) # 先确保输入框获得焦点 # 逐个发送每个字符 for char in target_password: action.send_keys(char) action.perform() # 执行所有动作排查浏览器扩展的干扰
很多密码管理类、脚本拦截类的浏览器扩展会修改输入框的行为,甚至可能把's'当成快捷键触发了别的操作。建议:- 用无痕模式启动ChromeDriver,代码里加参数:
from selenium.webdriver.chrome.options import Options chrome_options = Options() chrome_options.add_argument("--incognito") driver = webdriver.Chrome(options=chrome_options) - 或者直接禁用所有扩展测试:
chrome_options.add_argument("--disable-extensions")
- 用无痕模式启动ChromeDriver,代码里加参数:
升级Selenium版本
你当前用的Selenium 3.141.0虽然稳定,但后续的3.x版本修复了不少键盘事件相关的bug。可以尝试升级:pip install --upgrade selenium如果升级到Selenium 4的话,注意部分API有变动,比如
find_element_by_xpath需要换成find_element(By.XPATH, password_xpath),记得导入from selenium.webdriver.common.by import By。单独发送's'字符
先输入剩下的字符,再单独发送's',看看能不能正常输入:from selenium.webdriver.common.keys import Keys password_input.send_keys("paword") password_input.send_keys(Keys.S)
另外提一句,你之前尝试用\s是没用的,因为在Python字符串里\s代表的是空白字符(空格、制表符这类),不是字母's',所以只会输入反斜杠,这个是正常的语法规则,不用再试这个方法啦。
内容的提问来源于stack exchange,提问作者edmolten
相关产品推荐
相关产品推荐

