0

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? :(

Li54nder
  • 15
  • 4
  • first you could print generated string and use it directly in JavaScript in browser. Other problem can be that browser can remove this code from memory when you (re)load page. – furas Jun 16 '20 at 18:54
  • don't you get error when you run in console/terminal? When you use `format()` then `{...}` has special meaning in string - `open("{}"` but also in `function () {...}` - and you have to use `{{ }}` to use it as normal `{ }` - `function () {{....}}` – furas Jun 16 '20 at 19:36
  • Yes, you're right! curly braces were a problem. Thanks :) – Li54nder Jun 17 '20 at 22:19

1 Answers1

1

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

furas
  • 134,197
  • 12
  • 106
  • 148