Python: generic webbrowser.get().open() for chrome.exe does not work

前端 未结 6 1456
天命终不由人
天命终不由人 2020-12-11 09:48

I am on Python 2.7 (Win 8.1 x64) and I want to open a URL in Chrome. As Chrome is only natively supported in 3.3+, I was trying a generic call:

import webbro         


        
相关标签:
6条回答
  • 2020-12-11 10:18

    Following the suggestions above and working on Windows, to enable Firefox I have changed (and un-commented) the following line in the config file (note the %s at the end):

    c.NotebookApp.browser = 'C:/Program Files (x86)/Mozilla Firefox/firefox.exe %s'

    This worked for me. Thanks

    0 讨论(0)
  • 2020-12-11 10:19

    On Windows, you don't need to use UNIX-style path. Just wrap the raw string path to google.exe in escaped quotes, and append %s token after it, within an f-string:

    import webbrowser
    
    url = "https://docs.python.org/3/library/webbrowser.html"
    chrome = r"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"
    webbrowser.get(f"\"{chrome}\" %s").open_new_tab(url)
    
    0 讨论(0)
  • 2020-12-11 10:28

    You don't need to switch to Unix-style paths -- simply quote the executable.

    import webbrowser
    webbrowser.get('"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" %s').open('http://google.com')
    
    0 讨论(0)
  • 2020-12-11 10:30

    You have to use unix-style paths in the webbrowser.get call:

    webbrowser.get("C:/Program Files (x86)/Google/Chrome/Application/chrome.exe %s").open("http://google.com")
    

    This is because webbrowser internally does a shlex.split on the path, which will just erase Windows-style path separators:

    >>> cmd = "C:\\Users\\oreild1\\AppData\\Local\\Google\\Chrome\\Application\\chrome.exe %s"
    >>> shlex.split(cmd)
    ['C:Usersoreild1AppDataLocalGoogleChromeApplicationchrome.exe', '%s']
    >>> cmd = "C:/Users/dan/AppData/Local/Google/Chrome/Application/chrome.exe %
    s"
    >>> shlex.split(cmd)
    ['C:/Users/dan/AppData/Local/Google/Chrome/Application/chrome.exe', '%s']
    

    shlex will actually do the right thing here if given the posix=False keyword argument, but webbrowser won't supply that, even on Windows. This is arguably a bug in webbrowser.

    0 讨论(0)
  • 2020-12-11 10:32

    Worked for me

    code snippet:

    import webbrowser
    
    chrome_path = 'C:/Program Files (x86)/Google/Chrome/Application/chrome.exe %s'
    webbrowser.get(chrome_path).open('http://google.com')
    
    0 讨论(0)
  • 2020-12-11 10:33

    You can try this:

    import webbrowser
    
    chrome_path = "path_where_chrome_is_located"
    webbrowser.register('chrome', None, webbrowser.BackgroundBrowser(chrome_path))
    
    webbrowser.get('chrome').open('url')
    
    0 讨论(0)
提交回复
热议问题