selenium采集后Win平台下结束chrome进程的方法

from selenium import webdriver
from selenium.common.exceptions import TimeoutException,WebDriverException
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.remote.webelement import WebElement
import time
import psutil

page_encode = 'utf-8'


option=webdriver.ChromeOptions()
option.add_argument('headless') # 设置option
driver = webdriver.Chrome(chrome_options=option)  # 调用带参数的谷歌浏览器
#管理浏览器进程
driver_pid = driver.service.process.pid
processes = []
p = psutil.Process(driver_pid)
for x in p.children(recursive=True):
    processes.append(x.pid)
def get_web_info(url):    
	wait=WebDriverWait(driver,1)
	try:
		driver.get(url)
		//处理获取采集内容
		//....
		//处理完成后,退出driver
	    driver.quit()
	except TimeoutException as e:
	    print('timeout:',e)
	except WebDriverException as e:
	    print('webdriver error:',e)

if __name__ == '__main__':
    get_web_info("http://www.demo.com")
    #检查进程 杀掉进程
    if len(processes)>0:
        try:
            command = 'taskkill'
            for pid in processes:
                command += ' /pid %s /F' % pid
            os.system(command)
        except Exception as e:
            pass

你可能感兴趣的:(python,selenium,chrome,爬虫)