Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/selenium/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 打开';href';新选项卡中的变量_Python_Selenium_Automation_Selenium Chromedriver - Fatal编程技术网

Python 打开';href';新选项卡中的变量

Python 打开';href';新选项卡中的变量,python,selenium,automation,selenium-chromedriver,Python,Selenium,Automation,Selenium Chromedriver,我在python中使用selenium和chrome webdriver 我试图将“href”存储在一个变量中(本例中为“link”),并在一个新选项卡中打开它 我知道如何使用以下方式在新选项卡中打开专用网站: driver.execute_script("window.open('http://www.example.com', 'newtab')") 但是使用windows.open脚本只接受直接文本(据我所知),而不接受变量 代码如下: link = driver.find_elemen

我在python中使用selenium和chrome webdriver

我试图将“href”存储在一个变量中(本例中为“link”),并在一个新选项卡中打开它

我知道如何使用以下方式在新选项卡中打开专用网站:

driver.execute_script("window.open('http://www.example.com', 'newtab')")
但是使用windows.open脚本只接受直接文本(据我所知),而不接受变量

代码如下:

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
错误:

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

是否有其他方法可以在新选项卡中打开“链接”变量

在脚本中传递参数并不是将其视为url以使其成为url,请尝试使用此url。它对我有用

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

请让我知道这是否有效。

您传递了一个字符串以执行脚本,因此传递的不是字面上的“链接”,而是链接中的值(连接):

打开选项卡的另一种方法是将CTRL+T发送到浏览器:

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

如前所述,您可以在此处找到更多信息。

注意:@Benjamin最好提供完整的代码,以便可以复制和处理错误,因为用户不会编写代码来重新生成错误。否则,你会得到一个通用的解决方案,可能是“谢谢你”的翻版,它成功了!“+link+”是我缺少的语法,因为我是python新手。谢谢。嗨,伙计,“driver.execute_script(“window.open({},_blank');”。format(link))”给了我一个错误,但是!”driver.execute_脚本(“window.open(“{}”);“.format(link))”工作正常!谢谢你教我另一种处理这个问题的方法。我很感激。@Benjamin,上面提到的代码也应该能工作。我不知道为什么它不能工作。我已经测试过了,然后贴在这里。不管怎样,谢谢。如果这真的有帮助的话,另一个角度,很好!