kane.zorfy
kane.zorfy

Reputation: 1040

How to close the existing browser tab using the Python webbrowser package

Using Python webbrowser package I can open a new tab with a specified URL. Is there a way to close this tab? I referred the below official docs and nothing related to close action is mentioned.

Python webbrowser package doc: https://docs.python.org/3/library/webbrowser.html

Upvotes: 23

Views: 30749

Answers (4)

rav2001
rav2001

Reputation: 367

You can use pyautogui to close the browser tab when your task is fulfilled.

import time,webbrowser, pyautogui
def open_close(url="https://www.python.org/"):
    webbrowser.open(url)
    time.sleep(20)
    pyautogui.hotkey('ctrl', 'w')
    print("tab closed")

Upvotes: 16

M A R S
M A R S

Reputation: 11

u can close the tab by driver.close if u are using selenium package

Upvotes: -3

Bakkom
Bakkom

Reputation: 77

You could

Use a hotkey using the pykeyboard library which you can read about at https://github.com/SavinaRoja/PyUserInput

or the keyboard library at https://github.com/boppreh/keyboard

Another (but probably worse) option is:

You may use a "taskkill" command like

import os    
os.system("taskkill /im chrome.exe /f")

However, this will just kill all processes and close the chosen program (in this case chrome.exe)

(This also may delete data from the browser, f.eks. you lose all you're windows even tho you have chosen in settings to save them for next time you open your browser)

Upvotes: 0

XiR_
XiR_

Reputation: 222

No, webbrowser doesn't have methods to close tabs nor browser itself as you may see in its documentation page: https://docs.python.org/2/library/webbrowser.html

Upvotes: 5

Related Questions