Linux下Python Selenium ChromeDriver send_keys输入斜杠(/)失效问题
Linux下Selenium ChromeDriver send_keys输入斜杠丢失的解决方案
以下是几个可行的解决办法,按优先级排序:
1. 改用JavaScript注入设置内容
直接通过JavaScript给目标元素赋值,绕开send_keys的键盘模拟逻辑,这是最可靠的办法:
msg_q = '12/04/1983' msgBox_xpath = '//*[@id="main"]/footer/div[1]/div/span[2]/div/div[2]/div[1]/div/div/p' msgBox = wait.until(EC.element_to_be_clickable((By.XPATH, msgBox_xpath))) msgBox.click() # 针对p标签设置textContent,若是input元素则改用arguments[0].value = arguments[1] driver.execute_script("arguments[0].textContent = arguments[1];", msgBox, msg_q) msgBox.send_keys(Keys.ENTER)
2. 逐个字符输入并添加微小延迟
将字符串拆分为单个字符逐个输入,给Chrome足够的处理时间,避免字符丢失:
import time from selenium.webdriver.common.keys import Keys msg_q = '12/04/1983' msgBox_xpath = '//*[@id="main"]/footer/div[1]/div/span[2]/div/div[2]/div[1]/div/div/p' msgBox = wait.until(EC.element_to_be_clickable((By.XPATH, msgBox_xpath))) msgBox.click() for char in msg_q: msgBox.send_keys(char) time.sleep(0.1) # 0.1秒延迟可根据实际情况调整 msgBox.send_keys(Keys.ENTER)
3. 检查系统与Chrome的键盘/语言设置
Linux下键盘布局或Chrome语言设置可能导致斜杠映射异常:
- 切换系统键盘布局为美式英文(US)
- 在Chrome设置中,将默认语言改为English (US),重启Chrome和ChromeDriver后重试
4. 使用ActionChains模拟输入
利用ActionChains的链式操作发送文本,部分场景下比直接send_keys更稳定:
from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.common.keys import Keys msg_q = '12/04/1983' msgBox_xpath = '//*[@id="main"]/footer/div[1]/div/span[2]/div/div[2]/div[1]/div/div/p' msgBox = wait.until(EC.element_to_be_clickable((By.XPATH, msgBox_xpath))) msgBox.click() actions = ActionChains(driver) actions.send_keys(msg_q).perform() msgBox.send_keys(Keys.ENTER)
内容的提问来源于stack exchange,提问作者Nimesh
相关产品推荐
相关产品推荐

