使用Python的webbrowser.open()打开Chrome浏览器
根据文档 http://docs.python.org/3.3/library/webbrowser.html,这个功能应该是用默认浏览器打开网页的,但在我的电脑上却总是打开IE浏览器。我在网上搜索了一下,看到有人说需要注册浏览器,但我不太清楚怎么用webbrowser.register()这个方法,而且文档里的说明也不太清楚。我想知道怎么注册Chrome浏览器,这样我用webbrowser.open()打开的网址就能在Chrome里打开,而不是在IE里。
21 个回答
4
请查看这个:
import webbrowser
chrome_path = 'C:/Program Files (x86)/Google/Chrome/Application/chrome.exe %s'
webbrowser.get(chrome_path).open('http://docs.python.org/')
5
你也可以使用这个:
import webbrowser
chrome_path = r"C:\Program Files\Google\Chrome\Application\chrome.exe"
url = "http://docs.python.org/"
webbrowser.register('chrome', None, webbrowser.BackgroundBrowser(chrome_path))
webbrowser.get('chrome').open_new_tab(url)
22
import webbrowser
new = 2 # open in a new tab, if possible
# open a public URL, in this case, the webbrowser docs
url = "http://docs.python.org/library/webbrowser.html"
webbrowser.get(using='google-chrome').open(url,new=new)
你可以通过修改参数'using'来使用其他浏览器,具体方法可以参考这个链接。
37
在Windows系统中,路径使用的是类似UNIX的格式,所以要把反斜杠改成正斜杠。
webbrowser.get("C:/Program Files (x86)/Google/Chrome/Application/chrome.exe %s").open("http://google.com")
参考链接: Python: generic webbrowser.get().open() for chrome.exe does not work
140
你可以用 Chrome 的路径来调用 get() 函数。下面是一个例子——把 chrome_path 替换成你自己电脑上 Chrome 的正确路径。
import webbrowser
url = 'http://docs.python.org/'
# MacOS
chrome_path = 'open -a /Applications/Google\ Chrome.app %s'
# Windows
# chrome_path = 'C:/Program Files (x86)/Google/Chrome/Application/chrome.exe %s'
# Linux
# chrome_path = '/usr/bin/google-chrome %s'
webbrowser.get(chrome_path).open(url)