open 'href' variable in a new tab

淺唱寂寞╮ 提交于 2019-12-13 17:26:52

问题


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?


回答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




回答2:


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.



来源:https://stackoverflow.com/questions/54330431/open-href-variable-in-a-new-tab

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!