Selenium实现Twitter自动登录:execute_script模拟回车及元素定位问题
Twitter自动登录Selenium密码框交互问题解决
问题现象
- 开发Twitter自动登录机器人时,Selenium操作用户名/手机号输入框的
send_keys方法正常,但密码框调用send_keys时抛出错误:selenium.common.exceptions.ElementNotInteractableException: Message: element not interactable - 尝试用
driver.execute_script直接设置密码值成功,但用arguments[0].submit()模拟回车无效
问题根源
页面中存在不可交互的用户名input标签,导致定位密码框时选中了错误的元素,而非真正可交互的密码输入框。
解决方法
1. 正确定位密码输入框
放弃单独定位的方式,改用find_elements获取页面所有input元素的列表,选择对应索引的元素(这里是第二个):
password_input = driver.find_elements(By.TAG_NAME, "input")[1]
定位正确后,直接使用原生Selenium方法即可完成输入并模拟回车:
from selenium.webdriver.common.keys import Keys password_input.send_keys(TWITTER_PASSWORD) password_input.send_keys(Keys.ENTER)
2. 用JS模拟回车的正确方式
如果必须通过execute_script实现回车触发,不要用submit()(该方法针对表单元素,密码框本身不是表单),而是通过触发键盘事件实现:
driver.execute_script(""" const enterEvent = new KeyboardEvent('keydown', { key: 'Enter', code: 'Enter', bubbles: true, cancelable: true }); arguments[0].dispatchEvent(enterEvent); """, password_input)
内容的提问来源于stack exchange,提问作者Kbk12
相关产品推荐
相关产品推荐

