如何使用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 个回答
2
我知道这个问题已经很久了,但我也有过同样的疑问,这里是对我有用的解决办法:感谢@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秒钟让你输入。如果你没有输入东西,它会再次提示你输入。
4
你说得对,在JavaScript中使用提示框是正确的。不过,提示框的值应该赋给一个全局变量,这样你就可以在后面使用这个变量了。
可以这样写:
driver.execute_script("window.promptResponse=prompt('输入一些东西','一些东西')")
然后你可以从同一个全局变量中获取这个值。
a = driver.execute_script("var win = this.browserbot.getUserWindow(); return win.promptResponse")
你可能还需要转换一下返回的值。
希望这对你有帮助。
7
希望这能帮助到其他人:
# 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