在新标签页中打开"href"变量 [英] open 'href' variable in a new tab

查看:123
本文介绍了在新标签页中打开"href"变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将selenium和chrome webdriver与python一起使用.

I'm using selenium and chrome webdriver with python.

我正在尝试将"href"存储在变量中(在本示例中为"link"),然后在新标签页中将其打开.

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')")

但使用windows.open脚本仅接受直接文本(据我所知),而不接受变量.

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

以下是代码:

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

错误:

unknown error: link is not defined

还有其他方法可以在新标签页中打开链接"变量吗?

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

推荐答案

您将字符串传递给execute_script,因此,从字面上传递的不是链接,而是链接的值(连接):

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');")

打开标签页的另一种方法是向浏览器发送CTRL + T:

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)

如上所述,您可以在 28431765/open-web-in中找到更多信息-new-tab-selenium-python

这篇关于在新标签页中打开"href"变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆