0
browser.execute_script("window.open('about:blank', 'tab2');")
browser.switch_to.window("tab2")
browser.get('http://bing.com')

I was searching online ways to open a new tab using selenium in python, and the method of ctrl + t wasn't working on chrome so I stumbled on the above piece of code, however I am not able to understand what 'excute_script' does.

DebanjanB
  • 118,661
  • 30
  • 168
  • 217
  • See the link below for the javascript documentation: https://developer.mozilla.org/en-US/docs/Web/API/Window/open – Jortega Nov 24 '20 at 14:03

2 Answers2

3

execute_script method allows to execute JavaScript passed as string argument

Note that you can pass data from Python code into JavaScript code using arguments, e.g.

hello = "Hello"
friends = " friends"

browser.execute_script('alert(arguments[0], arguments[1]);', (hello,  friends))

enter image description here

DonnyFlaw
  • 373
  • 8
1

execute_script()

execute_script() synchronously executes JavaScript in the current window/frame.

execute_script(script, *args)

where:
    script: The JavaScript to execute
    *args: Any applicable arguments for your JavaScript.
    

This method is defined as:

   def execute_script(self, script, *args):
       """
       Synchronously Executes JavaScript in the current window/frame.

       :Args:
        - script: The JavaScript to execute.
        - \\*args: Any applicable arguments for your JavaScript.

       :Usage:
           ::

               driver.execute_script('return document.title;')
       """
       if isinstance(script, ScriptKey):
           try:
               script = self.pinned_scripts[script.id]
           except KeyError:
               raise JavascriptException("Pinned script could not be found")

       converted_args = list(args)
       command = None
       if self.w3c:
           command = Command.W3C_EXECUTE_SCRIPT
       else:
           command = Command.EXECUTE_SCRIPT

       return self.execute(command, {
           'script': script,
           'args': converted_args})['value']

Examples

A couple of examples:

  • To open a new blank tab:

    driver.execute_script("window.open('','_blank');")
    
  • To open a new tab with an url:

    driver.execute_script("window.open('https://www.google.com');")
    
  • To retrieve the page title:

    driver.execute_script('return document.title;')
    
  • To scroll inti view an element:

    driver.execute_script("arguments[0].scrollIntoView(true);",element)
    

References

You can find a couple of relevant detailed discussions in:

DebanjanB
  • 118,661
  • 30
  • 168
  • 217