如何在python 3中使用指定的Web浏览器打开URL

时间:2016-02-06 19:10:33

标签: python-3.x url

我正在python 3中创建一个程序,我希望用户使用指定的Web浏览器应用程序打开一个URL。我尝试使用subprocess.Popen([application, URL]),但它引发了FileNotFoundError。 非常感谢任何帮助。

编辑: 我忘了提到我使用的是Windows 10,这里是我收到的错误消息的副本:

Traceback (most recent call last):
File "C:\Users\[Name]\Desktop\AI.py", line 221, in <module>
subprocess.Popen(["google-chrome", "www.google.co.uk/"])
File "C:\Python34\lib\subprocess.py", line 859, in __init__
restore_signals, start_new_session)
File "C:\Python34\lib\subprocess.py", line 1112, in _execute_child
startupinfo)
FileNotFoundError: [WinError 2] The system cannot find the file specified

EDIT2: 这是我的结果,如果我尝试运行subprocess.Popen(["start", "chrome", "www.example.com/"])(如果我遗漏数组的"start",部分,我会得到同样的错误):

`Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    subprocess.Popen(["start", "chrome", "http://www.google.co.uk/"])
  File "C:\Python34\lib\subprocess.py", line 859, in __init__ restore_signals, start_new_session)
  File "C:\Python34\lib\subprocess.py", line 1112, in _execute_child
startupinfo)
FileNotFoundError: [WinError 2] The system cannot find the file specified`

2 个答案:

答案 0 :(得分:2)

或者您可以使用&#34; webbrowser&#34;模块

    import webbrowser

    url = 'www.google.com'

    webbrowser.open_new(url)

它将使用您的默认浏览器,无需查找您的机器&#39;特定浏览器路径。使其在工作空间之外变得更加通用和可用。

答案 1 :(得分:1)

import subprocess

subprocess.Popen([r"C:/Users/haral_000/AppData/Local/Google/Chrome/Application/chrome.exe", "example.com"])

&#39; r&#39;在字符串的开头使它成为原始字符串,这样反斜杠就不会被解释为转义符。

不是最优雅的解决方案,但它确实有效。我转到“开始”菜单并搜索Chrome,右键单击并选择&#34;打开文件位置&#34;,然后查看快捷方式的属性以查找exe文件的实际位置。毫无疑问,这个文件在你的另一个位置。当然不是我的用户名。