This opens a new tab in Firefox browser:
from selenium import webdriver
browser = webdriver.Firefox()
browser.execute_script('''window.open("https://www.google.com/","_blank");''')
As a reference, here is the Selenium documentation:
**execute_script**(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;’)
I have a link in a String which I wish to open in a new tab using javascript (via execute_script).
Tried the following but it gives an error:
link = 'https://www.bing.com/'
java_script = '\'\'\'window.open(\"' + link + '\",\"_blank\");\'\'\''
browser.execute_script(script)
Error:
selenium.common.exceptions.JavascriptException: Message: SyntaxError: unexpected token: string literal
-
1use r"string" or """string""" and just don't escape anythingAhmed I. Elsayed– Ahmed I. Elsayed2020年09月05日 18:06:06 +00:00Commented Sep 5, 2020 at 18:06
-
and to handle variables, execute say "let x = 2; return 2;" and capture this in a python variable, it will workAhmed I. Elsayed– Ahmed I. Elsayed2020年09月05日 18:06:27 +00:00Commented Sep 5, 2020 at 18:06
-
Check out f string, there are well suited for the case where you want to put a variable in the middle of a stringYacine Mahdid– Yacine Mahdid2020年09月05日 18:16:50 +00:00Commented Sep 5, 2020 at 18:16
1 Answer 1
F-string are well suited for that check them out
This will change your code to look like this:
from selenium import webdriver
browser = webdriver.Firefox()
link = 'https://www.bing.com/'
browser.execute_script(f"window.open('{link}','_blank');")
2 Comments
(f"window.open('{link}','_blank');") it works as wished. Thanks for helping!Explore related questions
See similar questions with these tags.