我正在寻找一种快速的方法来键入进入或返回键在硒。

不幸的是,我试图测试的表单(不是我自己的代码,所以我不能修改)没有Submit按钮。当手动使用它时,我只需输入Enter或Return。我怎么能做到这一点与硒类型命令,因为没有按钮点击?


当前回答

如果你只是想按Enter键(python):

from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys

action = ActionChains(driver)
action.send_keys(Keys.ENTER)
action.perform()

其他回答

Java远程控制:

selenium.keyPress("elementID", "\13");

对于Java的Selenium WebDriver(也就是Selenium 2):

driver.findElement(By.id("elementID")).sendKeys(Keys.ENTER);

Or,

driver.findElement(By.id("elementID")).sendKeys(Keys.RETURN);

在WebDriver中按Enter的另一种方法是使用Actions类:

Actions action = new Actions(driver);
action.sendKeys(driver.findElement(By.id("elementID")), Keys.ENTER).build().perform();

您可以在输入文本的元素对象上调用submit()。

或者,你也可以将Enter键发送给它,如下面的Python代码片段所示:

from selenium.webdriver.common.keys import Keys
element.send_keys(Keys.ENTER) # 'element' is the WebElement object corresponding to the input field on the page

当您不想搜索任何定位器时,您可以使用Robot类。例如,

Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);

你可以试试:

selenium.keyPress("id="", "\\13");

如果你是在这种情况下:

a)只是想按下键,但你没有一个特定的webElement来点击

b)您正在使用Selenium 2 (WebDriver)

那么解决方案是:

    Actions builder = new Actions(webDriverInstance);
    builder.sendKeys(Keys.RETURN).perform();