python seleniume 清除 chrom浏览器缓存

python seleniume 爬虫爬太久了,内存经常溢出,可以定期打开浏览器设置,来清除缓存。

代码:

def delete_cache(nCachec):
	driver.execute_script("window.open('');")
	time.sleep(1)
	driver.switch_to.window(driver.window_handles[-1])
	time.sleep(1)
	driver.get('chrome://settings/clearBrowserData')
	time.sleep(3)

	actions = ActionChains(driver)
	actions.send_keys(Keys.TAB * 4)
	actions.perform()

	#这里停一下 去掉cookie选项
	if nCachec != 1:
		actions = ActionChains(driver)
		actions.send_keys(Keys.ENTER)
		actions.perform()
		nCachec = 1

	actions = ActionChains(driver)
	actions.send_keys(Keys.TAB * 3)
	actions.perform()
	time.sleep(2)

	actions = ActionChains(driver)
	actions.send_keys(Keys.ENTER)
	actions.perform()
	time.sleep(3)

	driver.close()
	driver.switch_to.window(driver.window_handles[0])
	return nCachec

 

chromedriver的delete_all_cookies()函数是去cookie,想保存cookie的不要使用。

留下评论