Reputation:
So I'm writing a Python script to open internet links using cmd. For example:
import os
os.system('start http://stackoverflow.com/')
os.system('start http://www.google.com/')
os.system('start http://www.facebook.com/')
After I open them I do:
import time
time.sleep(60)
So I can wait a minute before doing anything else. What I can't seem to find anywhere is a way to close these tabs after I have opened them for 60 seconds? Is there a command I can use to close internet tabs in cmd?
Note: I'm using Windows 8, Python 2.7.9, and Google Chrome
Upvotes: 6
Views: 36794
Reputation: 61
You can simply use the keyboard shortcuts:
import keyboard
# here goes your code...
keyboard.press_and_release('ctrl+w') # closes the last tab
This will just close the last tab, not all (or as many as you want, starting from the last)
Upvotes: 5
Reputation: 6120
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
browser = webdriver.Firefox()
browser.get('http://stackoverflow.com')
main_window = browser.current_window_handle
browser.find_element_by_tag_name('body').send_keys(Keys.CONTROL + 't')
browser.get('http://stackoverflow.com/questions/tagged/django')
time.sleep(10)
browser.find_element_by_tag_name('body').send_keys(Keys.CONTROL + 'w')
Upvotes: 1
Reputation: 180401
You can start processes and then kill them after 60 seconds.
from subprocess import Popen, check_call
p1 = Popen('start http://stackoverflow.com/')
p2 = Popen('start http://www.google.com/')
p3 = Popen('start http://www.facebook.com/')
time.sleep(60)
for pid in [p1.pid,p2.pid,p3.pid]:
check_call(['taskkill', '/F', '/T', '/PID', str(pid)])
If you want to open a browser with three tabs then close I would use selenium or something similar:
import time
from selenium import webdriver
dr = webdriver.Chrome()
dr.get('http://stackoverflow.com/')
dr.execute_script("$(window.open('http://www.google.com/'))")
dr.execute_script("$(window.open('http://facebook.com/'))")
time.sleep(5)
dr.close()
dr.switch_to.window(dr.window_handles[-1])
dr.close()
dr.switch_to.window(dr.window_handles[-1])
dr.close()
Upvotes: 6
Reputation: 34207
Chrome got it's own process and resource management.
the lifecycle of a new chrome.exe <url>
is short. a new chrome
process communicate and passes the new tab request to another chrome
process and exits immediately. therefore the PID
of the new chrome.exe
is irrelevant and killing it will not going to close the newly opened tabs (as suggested in the sibling answer).
However, You can use this Naive alternative:
chrome.exe <url>
chrome.exe
processesfor example:
from subprocess import Popen
import time
urls = ['http://www.facebook.com/', 'http://www.google.com/']
for url in urls:
Popen(['start', 'chrome' , url], shell=True)
time.sleep(60)
Popen('taskkill /F /IM chrome.exe', shell=True)
chrome
instancesUpvotes: 1