python 的网络浏览器在 Windows 相对路径上启动 IE,而不是默认浏览器

发布于 2024-11-05 06:36:23 字数 772 浏览 2 评论 0原文

我正在尝试在默认浏览器中从 python 启动本地 html 文件(现在我的默认浏览器是 Google Chrome,如果我双击 .html 文件,Chrome 就会启动。)

当我使用 python 的 webbrowser.open( ),IE 会启动,但地址栏为空白。

Python 2.7.1 (r271:86832, Nov 27 2010, 17:19:03) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import webbrowser
>>> filename = 'test.html'
>>> webbrowser.open('file://'+filename)
True
>>> print(webbrowser.get().__class__.__name__)
WindowsDefault

我检查了我的默认程序,它们看起来是正确的。我用的是Win 7 SP1。为什么 Chrome 无法启动?

更新:代码将在未知的操作系统和机器上运行,因此不能选择硬编码或注册浏览器或路径更新。我正在考虑解析 file:// 的 url,然后进行 os.path.exists 检查和 os.path.realpath也许就是答案。

I'm attempting to launch a local html file from python in the default browser (right now my default is Google Chrome if I double-click on a .html file, Chrome launches.)

When I use python's webbrowser.open(), IE launches instead, with a blank address bar.

Python 2.7.1 (r271:86832, Nov 27 2010, 17:19:03) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import webbrowser
>>> filename = 'test.html'
>>> webbrowser.open('file://'+filename)
True
>>> print(webbrowser.get().__class__.__name__)
WindowsDefault

I've checked my default programs and they look correct. I'm on Win 7 SP1. Why is Chrome not launching?

Update: The code will be running on unknown OS's and machines, so hardcoding or registering browsers or path updates are not options. I'm thinking that parsing the url for file:// and then doing an os.path.exists check and os.path.realpath might be the answer.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(14

残疾 2024-11-12 06:36:23

我的主要问题是尝试将 file:// 添加到相对路径,导致 URL 错误。它可以通过以下方式修复:

webbrowser.open('file://' + os.path.realpath(filename))

使用 webbrowser.open 将尝试多种方法,直到一个“成功”,这是一个松散的定义。

WindowsDefault 类调用 os.startfile() 失败并返回 False。我可以通过在 Windows 运行命令中输入 URL 并看到错误消息而不是浏览器来验证这一点。

GenericBrowserBackgroundBrowser 都会使用一个 exe 调用 subprocess.Popen(),即使 URL 错误,也会成功,并返回 确实如此。 IE 没有给出任何有关该问题的指示,所有其他浏览器都有一条很好的消息说它们找不到该文件。

  1. GenericBrowser 由环境变量 BROWSER 设置,并且是第一个。
  2. WindowsDefault 是第二位。
  3. BackgroundBrowser 是最后一个,如果没有其他办法的话,它包含后备 IE。

这是我的原始设置:

>>> import webbrowser
>>> webbrowser._tryorder
['windows-default',
 'C:\\Program Files\\Internet Explorer\\IEXPLORE.EXE']
>>> webbrowser._browsers.items()
[('windows-default', [<class 'webbrowser.WindowsDefault'>, None]),
 ('c:\\program files\\internet explorer\\iexplore.exe', [None, <webbrowser.BackgroundBrowser object at 0x00000000022E3898>])]
>>>

这是修改环境变量后的设置:

C:>path=C:\Program Files (x86)\Mozilla Firefox;%path%

C:>set BROWSER=C:\Users\Scott\AppData\Local\Google\Chrome\Application\chrome.exe

C:>python
Python 2.7.1 (r271:86832, Nov 27 2010, 17:19:03) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import webbrowser
>>> webbrowser._tryorder
['C:\\Users\\Scott\\AppData\\Local\\Google\\Chrome\\Application\\chrome.exe',
 'windows-default',
 'firefox',
 'C:\\Program Files\\Internet Explorer\\IEXPLORE.EXE']
>>> webbrowser._browsers.items()
[('windows-default', [<class 'webbrowser.WindowsDefault'>, None]),
 ('c:\\program files\\internet explorer\\iexplore.exe',[None, <webbrowser.BackgroundBrowser object at 0x000000000235E828>]),
 ('firefox', [None, <webbrowser.BackgroundBrowser object at 0x000000000235E780>]),
 ('c:\\users\\scott\\appdata\\local\\google\\chrome\\application\\chrome.exe', [None, <webbrowser.GenericBrowser object at 0x000000000235E8D0>])]
>>>

webbrowser._tryorder 给出了尝试过的浏览器列表。注册 chrome 或添加浏览器环境变量或修改我的路径都会让我获得正确的浏览器和更好的错误消息。

感谢您的帮助,没有您的想法我无法解决这个问题。

My main issue was a bad URL by attempting prepend file:// to a relative path. It can be fixed with this:

webbrowser.open('file://' + os.path.realpath(filename))

Using webbrowser.open will try multiple methods until one "succeeds", which is a loose definition.

The WindowsDefault class calls os.startfile() which fails and returns False. I can verify that by entering the URL in the windows run command and seeing an error message rather than a browser.

Both GenericBrowser and BackgroundBrowser will call subprocess.Popen() with an exe which will succeed, even with a bad URL, and return True. IE gives no indication of the issue, all other browsers have a nice messages saying they can't find the file.

  1. GenericBrowser is set by the environment variable BROWSER and is first.
  2. WindowsDefault is second.
  3. BackgroundBrowser is last and includes the fall back IE if nothing else works.

Here is my original setup:

>>> import webbrowser
>>> webbrowser._tryorder
['windows-default',
 'C:\\Program Files\\Internet Explorer\\IEXPLORE.EXE']
>>> webbrowser._browsers.items()
[('windows-default', [<class 'webbrowser.WindowsDefault'>, None]),
 ('c:\\program files\\internet explorer\\iexplore.exe', [None, <webbrowser.BackgroundBrowser object at 0x00000000022E3898>])]
>>>

Here is my setup after modifiying the environment variables:

C:>path=C:\Program Files (x86)\Mozilla Firefox;%path%

C:>set BROWSER=C:\Users\Scott\AppData\Local\Google\Chrome\Application\chrome.exe

C:>python
Python 2.7.1 (r271:86832, Nov 27 2010, 17:19:03) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import webbrowser
>>> webbrowser._tryorder
['C:\\Users\\Scott\\AppData\\Local\\Google\\Chrome\\Application\\chrome.exe',
 'windows-default',
 'firefox',
 'C:\\Program Files\\Internet Explorer\\IEXPLORE.EXE']
>>> webbrowser._browsers.items()
[('windows-default', [<class 'webbrowser.WindowsDefault'>, None]),
 ('c:\\program files\\internet explorer\\iexplore.exe',[None, <webbrowser.BackgroundBrowser object at 0x000000000235E828>]),
 ('firefox', [None, <webbrowser.BackgroundBrowser object at 0x000000000235E780>]),
 ('c:\\users\\scott\\appdata\\local\\google\\chrome\\application\\chrome.exe', [None, <webbrowser.GenericBrowser object at 0x000000000235E8D0>])]
>>>

The webbrowser._tryorder gives the list of browsers tried. Registering chrome or adding a BROWSER env var or modifiying my path all would have gotten me the correct browser with a better error message.

Thanks for the help guys, I couldn't have solved this without your ideas.

审判长 2024-11-12 06:36:23

您可以使用 get(name) 来使用特定的浏览器。

您需要注册 Chrome 网络浏览器,因为它不需要似乎是预定义的浏览器类型之一,然后你应该能够做到这一点:

webbrowser.get('chrome').open('http://www.google.com')

更新:

实际上,您可能只能执行以下操作之一:

webbrowser.get('windows-default').open('http://www.google.com')
webbrowser.get('macosx').open('http://www.google.com')

文档没有显示 Linux 的预定义默认值。

You can use get(name) to use a specific browser.

You'll need to register the Chrome webbrowser, as it doesn't seem to be one of the predefined browser types, and then you should be able to do this:

webbrowser.get('chrome').open('http://www.google.com')

Update:

Actually, you might be able to just one of the following:

webbrowser.get('windows-default').open('http://www.google.com')
webbrowser.get('macosx').open('http://www.google.com')

The docs show no predefined defaults for Linux.

带刺的爱情 2024-11-12 06:36:23

这为我打开了一个新的 Chrome 选项卡,并且它仍然独立于操作系统:

webbrowser.get().open('http://www.google.com')

奇怪的是,如果没有 get() 调用,它仍然使用 IE。这看起来像是一个错误,但有一个简单的解决方法。

This opened a new Chrome tab for me, and it's still OS-independent:

webbrowser.get().open('http://www.google.com')

What's odd is that without the get() call, it still uses IE. This looks like a bug with a simple workaround.

魔法唧唧 2024-11-12 06:36:23

简而言之,使用 Windows 10,所有不包含 https://example.com 格式的完整 URL 的内容都会在 IE 中打开。例如,如果我说

webbrowser.open("https://www.example.com")

它将在 Chrome 中打开一个新选项卡,而

webbrowser.open("example.com")

将打开 IE。任何 .get() 都会导致它根本无法打开浏览器。

有点奇怪的行为,但我可以看到这是一个复杂的事情,而且很可能是操作系统造成了这种行为。

Using Windows 10, in short, everything that does not include a full URL in the https://example.com format is opened in IE for me. For example, if I say

webbrowser.open("https://www.example.com")

it will open a new tab in Chrome, while

webbrowser.open("example.com")

will open IE. Any .get() will cause it to not open a browser at all.

Kind of weird behaviour, but I can see that this is a complex thing do implement and likely the OS is to blame for this behavior.

坏尐絯℡ 2024-11-12 06:36:23

webbrowser 模块应该使用默认浏览器,因此这可能是一个错误。另一方面,请使用 docs 中的说明来解决您的问题:

如果环境变量BROWSER
存在,它被解释为覆盖
平台默认浏览器列表,
作为 os.pathsep 分隔的列表
浏览器按顺序尝试。当
列表部分的值包含
字符串 %s,那么它被解释为
文字浏览器命令行为
与替换的参数 URL 一起使用
对于 %s;如果该部分不包含
%s,它简单地解释为
要启动的浏览器的名称。

The webbrowser module is supposed to use the default browser, so this might be a bug. On the other hand, use this explanation from the docs to troubleshoot your problem:

If the environment variable BROWSER
exists, it is interpreted to override
the platform default list of browsers,
as a os.pathsep-separated list of
browsers to try in order. When the
value of a list part contains the
string %s, then it is interpreted as a
literal browser command line to be
used with the argument URL substituted
for %s; if the part does not contain
%s, it is simply interpreted as the
name of the browser to launch.

你的他你的她 2024-11-12 06:36:23

查看模块源代码,它首先尝试使用Windows默认浏览器,但如果它不起作用,它会搜索作为命令的常用浏览器名称,即。位于 PATH 变量中。尝试将网络浏览器的位置添加到您的路径中。

Looking at the module source code, it first tries to use the Windows default browser but if it doesn't work, it searches for common browser names that are commands, ie. that are in the PATH variable. Try adding the location of your web browser to your PATH.

笑红尘 2024-11-12 06:36:23

我用火狐也有同样的问题。 http://www.google.com 在 ff 中打开,而 file:///test.html 在中打开IE。

webbrowser doc 说:

请注意,在某些平台上,尝试
使用此函数打开文件名,
可以工作并开始运行
系统的关联程序。然而,
这既不受支持也不
便携式。

I have the same problem with firefox. http://www.google.com is opened in ff while file:///test.html is opened in IE.

webbrowser doc says:

Note that on some platforms, trying to
open a filename using this function,
may work and start the operating
system’s associated program. However,
this is neither supported nor
portable.

尘世孤行 2024-11-12 06:36:23

在 Python 3.6、Windows 10 上对我有用的是使用 register() 函数和 BackgroundBrowser 来登录我想要的浏览器:

import webbrowser

# Register your preferable browser
browser_path = 'C:/path/to/opera.exe'
webbrowser.register('opera', None, webbrowser.BackgroundBrowser(browser_path))

# Get an instance and launch your file
browser = webbrowser.get('opera') 
browser.open('html_file')

额外的观察 -

webbrowser 还有一个 <代码>GenericBrowser类。

查看,似乎BackgroundBrowser 在调用 subprocess.Popen() 时使用 start_new_session,而 GenericBrowser 则不使用。

我不知道该标志的确切功能。

但实际上,使用 BackgroundBrowser 切换到浏览器窗口,而 GenericBrowser 仅打开选项卡,但不切换。

What worked for me with Python 3.6, Windows 10, was using the register() function with BackgroundBrowser, to sign in my desired browser:

import webbrowser

# Register your preferable browser
browser_path = 'C:/path/to/opera.exe'
webbrowser.register('opera', None, webbrowser.BackgroundBrowser(browser_path))

# Get an instance and launch your file
browser = webbrowser.get('opera') 
browser.open('html_file')

Bonus observation -

webbrowser also has a GenericBrowser class.

Looking at the source, seems BackgroundBrowser uses start_new_session when calling subprocess.Popen(), whereas GenericBrowser does not.

I'm not aware of that flag's exact functionality.

Practically however, using BackgroundBrowser switches to the browser window, while GenericBrowser just opens the tab, but doesn't switch.

樱花坊 2024-11-12 06:36:23

这个问题只出现在 file:/// 协议 URL 上,这些 URL 可能没有注册到 chrome,所以 os.startfile() (这是 webbrowser.open 在 Windows 上尝试的第一件事)打开它们在 Internet Explorer 中。我认为将其他浏览器放入 PATH 中不会有帮助,因为在尝试路径中的浏览器之前仍然会调用 os.startfile() 。

可以做的是检查注册表中http://的默认浏览器(例如,通过检查注册表项HKEY_CLASSES_ROOT\http\shell \open\command)并将其用于 file:/// URL。不漂亮,但应该可以。

import _winreg
import webbrowser
import shlex
import subprocess

def win_browser_open(url):
    if url.startswith('file:///'):
        browser = _winreg.QueryValue(_winreg.HKEY_CLASSES_ROOT, r'http\shell\open\command')
        browser = browser.replace('%1', url)
        subprocess.Popen(shlex.split(browser))
    else:
        webbrowser.open(url)

This problem appears for me only with file:/// protocol URLs, which are probably not registered to chrome, so os.startfile() (which is the first thing webbrowser.open tries on Windows) opens them in Internet Explorer. I don't think putting your other browser in the PATH will help, since os.startfile() still gets invoked before even trying the browsers in the path.

What you can do, is to check the default browser for http:// in the registry (for instance, by checking the registry key HKEY_CLASSES_ROOT\http\shell\open\command) and use that one for file:/// URLs. Not pretty, but it should work.

import _winreg
import webbrowser
import shlex
import subprocess

def win_browser_open(url):
    if url.startswith('file:///'):
        browser = _winreg.QueryValue(_winreg.HKEY_CLASSES_ROOT, r'http\shell\open\command')
        browser = browser.replace('%1', url)
        subprocess.Popen(shlex.split(browser))
    else:
        webbrowser.open(url)
蓝眸 2024-11-12 06:36:23

使用这个:

import webbrowser
webbrowser.get('windows-default').open('http://www.google.com')

Use this:

import webbrowser
webbrowser.get('windows-default').open('http://www.google.com')
魄砕の薆 2024-11-12 06:36:23

由于所有答案都没有解决这个/我的问题,这种方式对我有用...(Windows)

命令需要位于列表中,而不是单个字符串中! (在本例中为“start”、“filepath”),shell 也需要为 True (windows)

import subprocess
subprocess.Popen(['start', 'C:/Users/User/Desktop/convert_report.html'], shell=True)

since all answers did not solve this/my issue, this way worked for me... (windows)

commands needs to be in a list, not in a single string! (in this case, "start", "filepath"), also shell needs to be True (windows)

import subprocess
subprocess.Popen(['start', 'C:/Users/User/Desktop/convert_report.html'], shell=True)
江南烟雨〆相思醉 2024-11-12 06:36:23

看来 webbrowser 模块无法在 cwd 中找到文件名,因为您通过快捷方式或终端打开了程序,因此 cwd 与程序的目录不同。

在这种情况下,在为 webbrowser.open 函数提供路径时,您必须将路径转换为程序目录的绝对路径。

程序的路径存储为 __file__ 全局常量。

您可以这样修复:

webbrowser.open(os.path.join(__file__, '..', filename))

我通过此解决方案解决了同样的问题。

It seems that webbrowser module couldn't find filename in cwd because you opened the program by shortcut or terminal, so cwd is different from the program's directory.

In that case, you have to convert the path into the absolute path of the program's directory when giving a path to webbrowser.open function.

The program's path is stored as __file__ global constant.

You can fix like that:

webbrowser.open(os.path.join(__file__, '..', filename))

I fixed the same problem by this solution.

治碍 2024-11-12 06:36:23

将 BROWSER 变量添加到系统变量中,并放置默认浏览器的路径。

Add a BROWSER variable to your system variables and put path of your default browser.

Spring初心 2024-11-12 06:36:23

我刚刚遇到了同样的问题,即使用 Internet Explorer 突然打开网页,该问题是在安装 Visual Studio 2017 后才开始的。我的猜测是 VS2017 安装了自己版本的 IE。
我的程序使用 webbrowser.open(url) 打开网站,但我从每个 URL 的开头删除了“https://”协议。现在,通过确保所有 URL 开头都有“https://”协议,问题就消失了,页面再次在 Chrome(我的 Windows 默认浏览器)中打开。

I just had the same issue of web pages suddenly opening with Internet Explorer, which only started after installing Visual Studio 2017. My guess is that VS2017 installed its own version of IE.
My program was opening websites using webbrowser.open(url), but I had stripped the 'https://' protocol from the beginning of each URL. Now, by making sure that all URLs have the 'https://' protocol at the beginning, the issue goes away and the pages are once again opened in Chrome (my Windows default browser).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文