2011-11-17 9 views
6

Vorrei consentire l'input dell'utente e prendere alcune decisioni basate su di esso. Se faccio questo:Come posso richiedere input usando Selenium/Webdriver e usare il risultato?

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

ottengo un bel pronta, ma non può usare il suo valore. C'è un modo per mostrare una casella di input all'utente e utilizzare il valore digitato lì?

EDIT: Questo è il mio script:

da selenium.webdriver importazione 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 

E questo esce con la seguente eccezione:

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 

Cosa non fare giusto?

EDIT: ho provato a fare come suggerito prestomanifesto, ecco l'output:

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 

risposta

1

Lei ha ragione nel utilizzando la finestra di prompt in javascript. Ma il valore del riquadro di richiesta deve essere assegnato a una variabile globale e quindi è possibile utilizzare questa variabile in un secondo momento. qualcosa di simile:

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

e quindi recuperare il valore dalla stessa variabile globale.

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

probabilmente è necessario effettuare il ritorno.

Spero che questo aiuti.

+0

Ho aggiornato la mia domanda con il risultato dell'esecuzione di codice. Riesci a capire cosa non sto facendo bene? – Geo

0

Perché non restituire il valore direttamente?

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

Lavora per me in C#. A dire il vero è una versione di selenio leggermente più vecchia, ma non mi aspetto che la funzione execute_script cambi molto.

+0

La cosa è, 'execute_script' restituisce immediatamente. Non blocca fino a quando non inserisco input. Vedi la mia modifica. – Geo

0

Si potrebbe utilizzare la tecnica suggerita here

L'idea di base è: Comandi

  • Problema Selenio fino al punto in cui si desidera catturare l'input dell'utente.
  • ottenere l'input dell'utente nella finestra della console con raw_input()
  • Continuare comandi tua Selenio

In Python, per esempio:

#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() 
+0

Mi piacerebbe tenerlo basato sulla GUI. – Geo

0

Se voi ragazzi utilizzando il selenio 2.28, come me, questo farà il trucco, proprio come @ Baz1nga dire

//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;"); 
0

Spero che questo aiuta gli altri:

# 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 
Problemi correlati