javascriptpythonseleniumexecute-script

Python selenium function driver.execute_script() won't execute my code in the script?


In my python script I use selenium function driver.execute_script() which won't execute all code in the script. Specifically, one code works but others not.

This code works:

driver.execute_script("""
        let w = window.open("{}","_blank");
        w.console.log("asdf");
        """.format(link))

But this here didn't work:

driver.execute_script("""
        let w = window.open("{}","_blank");
        w.addEventListener("DOMContentLoaded", function () {
            w.console.log("asdf");
        });
        """.format(link))

I need this event listener because the body of this function will work with DOM elements, but when I type code with an event listener python just skip executing the script, WHY? :(


Solution

  • When you use format() then {...} has special meaning in string - not only in open("{}" but also in function () {...} - and you have to use {{ }} to use it as normal { } -

    function () {{....}}
    

    More on PyFormat