0

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)") ?

4
  • 1
    driver.execute_script("alert('%s')" % keyy) Commented May 19, 2019 at 6:17
  • @thebjorn how to do it if I need to perform any numerical operation with a JavaScript variable inside driver.execute_script("<HERE>")? Commented Dec 12, 2020 at 18:00
  • @hafiz031 that is an entirely new question (please ask a new question - asking new questions in comments of 18+ month old questions is not likely to get any exposure). Commented Dec 13, 2020 at 8:46
  • @thebjorn here it is: stackoverflow.com/q/65274678/6907424 Commented Dec 13, 2020 at 10:45

1 Answer 1

1

you can use string formatting to put the value inside your string:

script = "alert('{}')".format(keyy)
driver.execute_script(script)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.