【python】UI自动化优化浏览器重复打开和跑脚本时电脑无法做其他工作的问题

1、改动common1:

import time
import json
import xlrd
import os
from webdriver_manager.chrome import ChromeDriverManager
from seleniumwire import webdriver
from selenium.webdriver.chrome.options import Options

#浏览器后端运行,一边操作其他的事,一边跑自动化脚本两不误
chrome_options = Options()
chrome_options.add_argument('--headless')

class common2:

def __init__(self):
self.config = {'url': None,
'session_id': None,
'new': True}
#如果存在txt,就关掉新开的浏览器,运行旧的浏览器
if os.path.exists('config.txt'):
self.config = json.loads(open('config.txt').read())
self.config['new'] = False
self.driver = webdriver.Remote(command_executor=self.config['url'], desired_capabilities={},
options=chrome_options)
self.driver.close()
self.driver.session_id = self.config['session_id']
#如果不存在,就把新开浏览器,然后写入txt
else:
# 调用webdeiver
self.driver = webdriver.Chrome(ChromeDriverManager().install(), options=chrome_options)
self.config['url'] = self.driver.command_executor._url
self.config['session_id'] = self.driver.session_id
with open('config.txt', 'w') as f:
f.write(json.dumps(self.config))

def set_header(self, request):
# 添加header
request.headers['***'] = '***'

def URL(self):
# 调用系统地址

return "https://www.pangle.cn/"

def login(self):
#如果是新的,就直接允许
if self.config['new']:
# 调试窗口大小、设置隐式等待、添加herder
self.driver.maximize_window()
self.driver.implicitly_wait(10)
self.driver.request_interceptor = self.set_header
self.driver.get(self.URL())
# 调用cookie
wb = xlrd.open_workbook('cookie.xlsx')
sheel = wb.sheet_by_name('sheet1')
for row in range(1, sheel.nrows):
self.driver.add_cookie({'name': sheel.cell_value(row, 0), 'value': sheel.cell_value(row, 1),
'domain': sheel.cell_value(row, 2), 'path': sheel.cell_value(row, 3)})
# 刷新页面
self.driver.refresh()
# 进入首页

        self.driver.get('https://www.pangle.cn/union/media/union')
       #关闭弹窗提示
time.sleep(5)
self.driver.find_elements_by_class_name('byted-btn')[4].click()
time.sleep(5)
self.driver.find_elements_by_class_name('byted-btn')[4].click()
#如果是旧的,就刷新到页面首页,开始运行下一个case
else:
self.driver.get('https://www.pangle.cn/union/media/union')
return self.driver
2、改动run_all_cases
末尾加上:
#删除文件,不删会报错
if os.path.exists('config.txt'):
os.remove('config.txt')
3、在case里面,不用再加quit()了,但最后运行完剩下的那一个要手动关闭

 缺陷:不能单个调试case

原文地址:https://www.cnblogs.com/luoguoxing/p/14924263.html