简体   繁体   中英

Opening tabs in browser with a variable link

Im using python and selenium, trying to open a new tab. The send_keys function is not opening the tabs but execute_script does. My issue is I have a url that is saved in a variable, and I need to pass that into the script, but I get an error.

Code:

src = 'http://yahoo.com'
driver.execute_script("window.open(" + src + ",'_blank');")

Error Message:

selenium.common.exceptions.WebDriverException: Message: unknown error: Runtime.evaluate threw exception: SyntaxError: missing ) after argument list

Also tried, does not work:

driver.find_element_by_tag_name('body').send_keys(Keys.COMMAND + 't')

driver.find_element_by_tag_name('body').send_keys(Keys.CONTROL + 't')

Does work, but url is hardcoded:

driver.execute_script("window.open('http://www.google.com/','_blank');")

You can use format to insert a variable.

An example:

driver = webdriver.Chrome(executable_path="/tmp/chromedriver")

link = 'http://example.com'
driver.execute_script('window.open("{}","_blank");'.format(link))
driver.switch_to.window(driver.window_handles[-1])

this worked:

driver.execute_script('''window.open('',"_blank");''')
driver.switch_to.window(driver.window_handles[-1])
driver.get(src)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM