Selenium WebDriver Python:如何阻止'send_keys'发送字符串后按下回车键

0 投票
1 回答
956 浏览
提问于 2025-04-18 15:38

我正在尝试通过Twitter自动登录一个网站,为了输入Twitter的登录信息,我在Selenium WebDriver中使用了elem.send_keys("username")这个方法。

这个方法似乎在发送字符串后也会“按下”回车,这就成了一个问题,因为这会导致登录表单在我还没输入密码之前就被提交了,页面刷新后,之前输入的用户名就消失了,导致无法登录。

我该如何发送键盘输入而不让回车也被提交呢?谢谢。

Python版本:3.4.1,Selenium版本:2.42.1,操作系统:Mac OSX 10.9.4

编辑:

这是我与浏览器中元素进行交互的方式,使用了try/except来防止出现StaleElementReference错误:

found = False
while not found:
    try:
        enterPassword = driver.find_element_by_id("password")
        enterPassword.send_keys(twPassword)
        found = True
    except:
        pass

这可能是问题所在吗?

1 个回答

0

你能测试一下这个在你那儿能提交吗?(在我这儿不行)

from selenium import webdriver as driver

browser = driver.Firefox()
browser.get("http://www.google.com")
print browser.find_element_by_name("q").send_keys('Searchstring')

顺便提一下:等待元素出现时,应该使用明确的等待。

from selenium.webdriver.support import expected_conditions as EC

wait = WebDriverWait(driver, 10)
element = wait.until(EC.presence_of_element_located((By.ID,'someid')))

阅读文档

撰写回答