How to close the existing browser tab using the Python webbrowser package
Asked Answered
E

4

23

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

Ethnogeny answered 19/5, 2015 at 12:52 Comment(3)
The webbrowser package cannot directly interact with your browser. It only uses OS functionality to open an URL, which works exactly the same way as if you click on a link in a third party program, e.g. an office or PDF document. There is simply no equivalent functionality to close a tab (that would be a bad idea for many reasons - you want acrobat or office to be able to open a tab, but not to be able to close random tabs), so the answer to your question is that it's not possible.Patois
Thanks for such a clear explanation. Is there a way to close an active tab in chrome browser using python.Ethnogeny
@l4mpi: IMHO that should have been an answer instead of a comment. :-)Subjugate
P
14

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")
Physicality answered 15/8, 2021 at 14:5 Comment(0)
C
5

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

Cyrillus answered 9/6, 2015 at 11:17 Comment(0)
T
0

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)

Triciatrick answered 16/2, 2019 at 7:45 Comment(0)
S
-3

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

Stenophyllous answered 1/6, 2021 at 17:59 Comment(1)
Welcome to SO, please have a read at stackoverflow.com/help/how-to-answerKimberelykimberlee

© 2022 - 2024 — McMap. All rights reserved.