如何使用Selenium / Webdriver提示输入并使用结果?

时间:2011-11-17 22:30:03

标签: python selenium webdriver

我想允许用户输入并根据它做出一些决定。如果我这样做:

driver.execute_script("prompt('Enter smth','smth')")

我得到了一个很好的提示,但我无法使用它的价值。有没有办法向用户显示输入框,并使用那里输入的值?

编辑:这是我的剧本:

from selenium.webdriver import Firefox

if __name__ == "__main__":
    driver = Firefox()
    driver.execute_script("window.promptResponse=prompt('Enter smth','smth')")
    a = driver.execute_script("var win = this.browserbot.getUserWindow(); return win.promptResponse")
    print "got back %s" % a

然后以下列例外退出:

    a = driver.execute_script("var win = this.browserbot.getUserWindow(); return win.promptResponse")
  File "c:\python26\lib\site-packages\selenium-2.12.1-py2.6.egg\selenium\webdriver\remote\webdriver.py", line 385, in ex
ecute_script
    {'script': script, 'args':converted_args})['value']
  File "c:\python26\lib\site-packages\selenium-2.12.1-py2.6.egg\selenium\webdriver\remote\webdriver.py", line 153, in ex
ecute
    self.error_handler.check_response(response)
  File "c:\python26\lib\site-packages\selenium-2.12.1-py2.6.egg\selenium\webdriver\remote\errorhandler.py", line 110, in
 check_response
    if 'message' in value:
TypeError: argument of type 'NoneType' is not iterable

我做得不对?

编辑:我试着像prestomanifesto那样建议,这是输出:

In [1]: from selenium.webdriver import Firefox

In [2]: f = Firefox()

In [3]: a = f.ex
f.execute              f.execute_async_script f.execute_script

In [3]: a = f.execute_script("return prompt('Enter smth','smth')")

In [4]: a
Out[4]: {u'text': u'Enter smth'}

In [5]: a
Out[5]: {u'text': u'Enter smth'}

In [6]: class(a)
  File "<ipython-input-6-2d2ff4f61612>", line 1
    class(a)
         ^
SyntaxError: invalid syntax


In [7]: type(a)
Out[7]: dict

8 个答案:

答案 0 :(得分:2)

使用javascript中的提示框是正确的。但是应该将提示框值分配给全局变量,然后您可以稍后使用此变量。 像这样的东西:

driver.execute_script("window.promptResponse=prompt('Enter smth','smth')")

然后从同一个全局变量中检索值。

a = driver.execute_script("var win = this.browserbot.getUserWindow(); return win.promptResponse")

你可能需要施放回报。

希望这有帮助。

答案 1 :(得分:1)

Tkinter是基于GUI的库,可用于在运行时从用户处获取输入。除非用户输入信息,否则这将使程序处于等待状态。对于预先设计的对话框,您可以参考此link。尽管已经晚了,但也许会对其他人有所帮助。

答案 2 :(得分:1)

基于其他答案,我构建了适用于我的以下代码:


def is_alert_present(driver):
    try:
        driver.switch_to.alert
        return True
    except exceptions.NoAlertPresentException:
        return False


def prompt_user(driver, text):

    driver.execute_script('var a = prompt ("{}");document.body.setAttribute("data-id", a)'.format(text))
    while is_alert_present(driver):
        sleep(4)
    v = driver.find_element_by_tag_name('body').get_attribute('data-id')

    return v if v != 'null' else None

答案 3 :(得分:0)

为什么不直接返回值?

if __name__ == "__main__":
    driver = Firefox()
    a = driver.execute_script("return prompt('Enter smth','smth')")
    print "got back %s" % a

在C#中为我工作。不可否认,这是一个稍微陈旧的Selenium版本,但我不希望execute_script功能发生太大变化。

答案 4 :(得分:0)

您可以使用建议的技术here

基本理念是:

  • 发布Selenium命令,直至您想要捕获用户输入。
  • 使用raw_input()
  • 在控制台窗口中获取用户输入
  • 继续您的Selenium命令

例如在Python中:

#Navigate to the site
driver.Navigate().GoToUrl("http://www.google.com/")
#Find the search box on the page
queryBox = self.driver.FindElement(By.Name("q"))
#Wait for user text input in the console window
text = raw_input("Enter something")
#Send the retrieved input to the search box
queryBox.SendKeys(text)
#Submit the form
queryBox.Submit()

答案 5 :(得分:0)

希望这有助于其他人:

# selenium (3.4.1)  python (3.5.1)
driver.execute_script("var a = prompt('Enter Luffy', 'Luffy');document.body.setAttribute('data-id', a)")
time.sleep(3)  # must 
print(self.driver.find_element_by_tag_name('body').get_attribute('data-id'))   # get the text

答案 6 :(得分:0)

我知道这是一个古老的问题,但我也有同样的问题,这对我有用:对@Devin表示感谢

from selenium.common.exceptions import UnexpectedAlertPresentException

while True:
    try:
        driver.execute_script("var a = prompt('Enter Luffy', 'Luffy');document.body.setAttribute('user-manual-input', a)")
        sleep(5)  # must 
        print(driver.find_element_by_tag_name('body').get_attribute('user-manual-input')) # get the text
        break

     except (UnexpectedAlertPresentException):
        pass

提示将等待5秒钟进行输入。如果未提供任何输入,它将提示用户再次输入。

答案 7 :(得分:-1)

如果你们像我一样使用硒2.28,这就像@ Baz1nga说的那样

//Open the prompt inbox and setup global variable to contain the result
WebDriver driver = new FirefoxDriver();
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("window.promptResponse = prompt(\"Please enter captcha\");");

//Handle javascript prompt box and get value. 
Alert alert = driver.switchTo().alert();
try {
  Thread.sleep(6000);
} catch (Exception e)
{
  System.out.println("Cannot sleep because of headache");
}
alert.accept();
String ret = (String) js.executeScript("return window.promptResponse;");