webbrowser模組(簡單)
開啟網頁於預設瀏覽器
import webbrowserurl = "http://google.com" # 注意:"http://"不可省略webbrowser.open(url)webbrowser.open_new(url)webbrowser.open_new_tab(url)
Display url using the browser handled by this controller. If new is 1, a new browser window is opened if possible. If new is 2, a new browser page (“tab”) is opened if possible.
開啟網頁於瀏覽器開啟
使用 webbrowser.get 取得不同瀏覽器的controller,如’mozilla’、’firefox’、’macos’(表示macos default)、’windows-default’、’safari’、’google-chrome’與’chrome’等,其他可參考[1]。
import webbrowserurl = "http://google.com" # 注意:"http://"不可省略f_ctrler = webbrowser.get("firefox") # 取得firefox controllerf_ctrler.open(url)
動態取得目前有哪些controller可使用。
print(webbrowser._tryorder)['MacOSX', 'chrome', 'firefox', 'safari']
其他方法(複雜)
法一
from threading import Timer
from time import sleep
import subprocess
import platform
# Hint 1: to enable F11 use --start-fullscreen instead of --kiosk, otherwise Alt+F4 to close the browser
# Hint 2: fullscreen will only work if chrome is not already running
platform_browser = {
'Windows': r'"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --kiosk http://stackoverflow.com',
'Linux' : ['/usr/bin/chromium-browser', '--kiosk', 'http://stackoverflow.com']
}
browser = None
def open_browser():
global browser
platform_name = platform.system()
if platform_name in platform_browser:
browser = subprocess.Popen(platform_browser[platform_name])
else:
print(":-(")
Timer(1, open_browser).start() # delayed start, give e.g. your own web server time to launch
sleep(20) # start e.g. your python web server here instead
browser.kill()
法二
#!/usr/bin/env python3 import webbrowser a_website = "https://www.google.com" # Linux # chrome_cmd = "/usr/bin/google-chrome %s" # Windows # chrome_cmd = "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe %s" # Mac chrome_cmd = "open -a /Applications/Google\ Chrome.app %s" webbrowser.get(chrome_cmd).open_new_tab(a_website)