Selenium ChromeDriver在Ubuntu下send_keys乱序,Windows下正常
解决Selenium send_keys在Ubuntu下内容乱序的问题
问题分析
代码在Windows下格式正常,但Ubuntu下send_keys输出乱序、print内容正常,核心原因是:
- 跨系统换行符差异(Windows用
\r\n,Linux用\n),部分输入框对换行符解析不一致 - Linux下ChromeDriver模拟键盘输入的时序问题,一次性输入大量带换行的内容时,输入顺序出现错乱
解决方案
1. 统一换行符适配系统
使用os.linesep自动适配当前系统的换行符,避免跨系统格式差异:
import os from selenium import webdriver search_word = 'Witty' my_link = 'https://w1tty.page.link/ZXAy8GSX7XxpnHZC7' # 用os.linesep替换手动换行 message = ( f'Hello,{os.linesep}{os.linesep}' f'if you need a link for {search_word} here it is:{os.linesep}{os.linesep}' f'{my_link}{os.linesep}{os.linesep}' f'Greetings{os.linesep}' f'RZX' ) element = driver.find_element_by_xpath("//div[@placeholder='Please write your message here...']") element.send_keys(message)
2. 使用ActionChains分步模拟输入
通过ActionChains模拟真实用户的点击-输入流程,降低时序错乱概率:
from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains search_word = 'Witty' my_link = 'https://w1tty.page.link/ZXAy8GSX7XxpnHZC7' message = ( 'Hello,\n\n' f'if you need a link for {search_word} here it is:\n\n' f'{my_link}\n\n' 'Greetings\n' 'RZX' ) element = driver.find_element_by_xpath("//div[@placeholder='Please write your message here...']") # 先清空输入框(如果有默认内容) element.clear() # 用ActionChains执行输入 actions = ActionChains(driver) actions.click(element).send_keys(message).perform()
3. 直接通过JavaScript设置内容(最稳定)
绕过Selenium的键盘模拟,直接操作DOM设置输入框内容,彻底避免输入时序问题:
from selenium import webdriver search_word = 'Witty' my_link = 'https://w1tty.page.link/ZXAy8GSX7XxpnHZC7' message = ( 'Hello,\n\n' f'if you need a link for {search_word} here it is:\n\n' f'{my_link}\n\n' 'Greetings\n' 'RZX' ) element = driver.find_element_by_xpath("//div[@placeholder='Please write your message here...']") # 对于contenteditable类型的div,用innerText设置内容 driver.execute_script("arguments[0].innerText = arguments[1];", element, message) # 如果是普通input框,改用value属性: # driver.execute_script("arguments[0].value = arguments[1];", element, message)
内容的提问来源于stack exchange,提问作者RZX
相关产品推荐
相关产品推荐

