1. 程式人生 > 其它 >【python】UI自動化優化瀏覽器重複開啟和跑指令碼時電腦無法做其他工作的問題

【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.find_element_by_xpath('/html/body/di v[1]/div/div/header/section/button').click()
       #關閉彈窗提示
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()了,但最後執行完剩下的那一個要手動關閉