Reputation: 2034
I'm trying to execute a little Python script which runs a function via selenium in a firefox browser.
Now I use:
pageurl = 'https://www.google.com'
driver.get(pageurl)
driver.execute_script("alert('hi')")
Which indeed runs the alert box on in firefox, and shows 'hi'.
I want to be able to let alert output/run a variable.
So like this:
pageurl = 'https://www.google.com'
driver.get(pageurl)
keyy = 'blabla'
driver.execute_script("alert(keyy)")
But instead of running the alert command, I get an error.
Traceback (most recent call last):
File "C:\Users\Jeroen\AppData\Local\Programs\Python\Python37-32\test.py", line 29, in <module>
driver.execute_script("alert(keyy)")
File "C:\Users\Jeroen\AppData\Local\Programs\Python\Python37-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 636, in execute_script
'args': converted_args})['value']
File "C:\Users\Jeroen\AppData\Local\Programs\Python\Python37-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 321, in execute
self.error_handler.check_response(response)
File "C:\Users\Jeroen\AppData\Local\Programs\Python\Python37-32\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.JavascriptException: Message: ReferenceError: keyy is not defined
How should I be writing driver.execute_script("alert(keyy)")
?
Upvotes: 0
Views: 3582
Reputation: 60604
you can use string formatting to put the value inside your string:
script = "alert('{}')".format(keyy)
driver.execute_script(script)
Upvotes: 1