有什么方法可以在 colab 中使用 python 的网络浏览器模块打开新标签页?

Is there any way to open a new tab using a webbrowser module of python in colab?

import webbrowser
webbrowser.open_new_tab('www.google.com')

我正在使用 Google-colaboratory 并得到 False 作为输出。取而代之的是,它应该打开一个 url 或 Google 的新选项卡。它在 python 3.7 和 PyCharm 中运行良好。

我知道用 colab 编写的程序在 google 云上运行,google 云中没有浏览器。

除了使用 selenium 工具,在 google-colab 中还有其他方法可以做到这一点吗?

提前致谢!

不,在 Colab 中无法通过 Python 的 webbrowser 包控制您的浏览器。原因是您的浏览器是 运行 在您的本地计算机上,而 Colab 中的 Python 代码是 运行 在 Google Cloud 中的虚拟机上。

您可以通过 Colab 打开新标签页的唯一方法是注入 javascript 代码,让您的浏览器打开新标签页;例如:

%%javascript
window.open('https://colab.research.google.com', '_blank');

但请注意,您的浏览器可能会阻止 windows 以这种方式打开。

有时,如果打开网页所需的代码行需要包含在条件语句或循环中,或者任何无法将 %%javascript 写为单元格第一行的情况,请使用此代码

from IPython.display import Javascript
def open_web():
    url = 'https://www.google.com/'
    display(Javascript('window.open("{url}");'.format(url=url)))