7
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.

1

2 Answers 2

17

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

Sign up to request clarification or add additional context in comments.

Comments

5

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:

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.