如何使用cmd/Python关闭Internet选项卡?

5 python cmd python-2.7

所以我正在编写一个Python脚本来使用cmd打开Internet链接.例如:

import os
os.system('start http://stackoverflow.com/')
os.system('start http://www.google.com/')
os.system('start http://www.facebook.com/')
Run Code Online (Sandbox Code Playgroud)

我打开它后,我做:

import time 
time.sleep(60)
Run Code Online (Sandbox Code Playgroud)

所以我可以等一下再做其他事情.在我打开它们60秒后,我无法在任何地方找到的方法是关闭这些标签的方法吗?我可以使用命令关闭cmd中的Internet选项卡吗?

注意:我使用的是Windows 8,Python 2.7.9Google Chrome

Pad*_*ham 7

您可以启动进程,然后在60秒后终止它们.

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)])
Run Code Online (Sandbox Code Playgroud)

替换-OS-系统

如果你想打开一个带有三个标签的浏览器然后关闭我将使用selenium或类似的东西:

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()
Run Code Online (Sandbox Code Playgroud)

chromedriver,selenium


小智 5

您可以简单地使用键盘快捷键:

import keyboard

# here goes your code... 

keyboard.press_and_release('ctrl+w') # closes the last tab
Run Code Online (Sandbox Code Playgroud)

这只会关闭最后一个选项卡,而不是所有选项卡(或者从最后一个选项卡开始,根据需要关闭多个选项卡)