1

I'm using selenium and chrome webdriver with python.

I'm trying to store 'href' inside a variable ('link' for this example) and open it in a new tab.

i know how to open a dedicated website in a new tab using this way:

driver.execute_script("window.open('http://www.example.com', 'newtab')")

but using windows.open script accepts only direct text(as far as i know) and not variables.

Here is the code:

link = driver.find_element_by_class_name('asset-content').find_element_by_xpath(".//a[@class='mr-2']").get_attribute("href") #assigning 'href' into link variable. works great. 
driver.execute_script("window.open(link, 'newtab')") #trying to open 'link' in a new tab

The error:

unknown error: link is not defined

Any other way i can open 'link' variable in a new tab?

Benjie
  • 35
  • 5
  • Note: @Benjamin it's best to provide the entire code so that the error can be reproduced and worked with, as users won't write code to re-produce the error. Otherwise, you'll get a generic solution – chitown88 Jan 23 '19 at 16:32
  • 3
    Possible duplicate of [Open web in new tab Selenium + Python](https://stackoverflow.com/questions/28431765/open-web-in-new-tab-selenium-python) – chitown88 Jan 23 '19 at 16:36

2 Answers2

1

Passing the parameter in scripts is not treating as url to make it url try This one. It works for me.

driver.execute_script("window.open('{},_blank');".format(link))

Please let me know if this work.

KunduK
  • 32,888
  • 5
  • 17
  • 41
  • Hi Man, 'driver.execute_script("window.open('{},_blank');".format(link))' gave me an error but! 'driver.execute_script("window.open('{});".format(link))' worked! thanks for teaching me another way to hande this. i appriciate that. – Benjie Jan 23 '19 at 21:06
  • @Benjamin, The above mentioned code should also work.I don’t know why it’s not working. I have tested and then posted here.Anyways thanks.If it really helps that matters – KunduK Jan 24 '19 at 00:13
  • another perspective, Nice ! – Dev Jan 24 '19 at 07:10
1

You passing on a string to execute_script, so pass not a 'link' literally, but the value from the link (concatenate):

driver.execute_script("window.open('"+link+"','icoTab');")

Another way to open a tab is sending CTRL+T to the browser:

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

As mentioned, you can find more here 28431765/open-web-in-new-tab-selenium-python

Litvin
  • 330
  • 1
  • 9
  • Thanks man it worked! "+link+" was the syntax i was missing cause im new to python. i appreciate that. – Benjie Jan 23 '19 at 21:03