Python 2.7 更改 webbrowser.open 的默认浏览器
我正在尝试打开一个我写的网页,这个网页保存在本地服务器上。一切都很好,但它默认用IE浏览器打开,而不是我设置的Chrome。Chrome是我的默认浏览器,但我在网上找不到任何有用的建议。
示例代码:
import webbrowser
webbrowser.open('192.168.1.254:1337/SmartFormTest1.php')
提前谢谢你们!
4 个回答
0
我的浏览器默认设置是正确的,使用的是Brave浏览器,只需要在webbrowser.py
文件中进行更改。具体是在第539到563行
。
在第540行
,只需要把操作系统的路径改成你想用的浏览器的路径。比如,如果你想用Brave浏览器,就把给iexplorer
变量的路径改成这样:
iexplore = os.path.join(os.environ.get("PROGRAMFILES", "C:\\Program Files"),
"BraveSoftware\\Brave-Browser\\Application\\brave.EXE")
0
在Windows系统上,下面的代码对我来说是有效的。
chrome_path = '"C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe" %s'
webbrowser.get(chrome_path).open('google.com')
1
根据文档,你可以通过以下几种方式来解决这个问题:
- 设置一个环境变量叫做
BROWSER
- 使用
webbrowser.get('chrome')
来获取Chrome浏览器的控制实例,然后用这个实例来进行浏览 - 检查你的设置——你确定你的默认浏览器设置正确吗?它在你的开始菜单的“互联网”图标下能找到吗?
2
好的,我找到了问题所在。我的浏览器默认设置是正确的,使用的是Chrome,问题出在webbrowser.py这个文件里。第539到563行的内容是:
if sys.platform[:3] == "win":
class WindowsDefault(BaseBrowser):
def open(self, url, new=0, autoraise=True):
try:
os.startfile(url)
except WindowsError:
# [Error 22] No application is associated with the specified
# file for this operation: '<URL>'
return False
else:
return True
_tryorder = []
_browsers = {}
# First try to use the default Windows browser
register("windows-default", WindowsDefault)
# Detect some common Windows browsers, fallback to IE
iexplore = os.path.join(os.environ.get("PROGRAMFILES", "C:\\Program Files"),
"Internet Explorer\\IEXPLORE.EXE")
for browser in ("firefox", "firebird", "seamonkey", "mozilla",
"netscape", "opera", iexplore):
if _iscommand(browser):
register(browser, None, BackgroundBrowser(browse()
我只需要在列表中添加“chrome”这个选项就可以了。