提交 ce47ccf9 authored 作者: 陈泽健's avatar 陈泽健

refactor(预定系统): 优化代码结构和功能

- 修改 base.py 中的 ChromeDriver 路径设置
- 重构 StableMQTTClient 类,增加连接重试和消息重发功能
- 新增安卓信息全局定时重启脚本
- 扩展安卓信息批量更新模拟脚本,增加下载进度显示和重试机制
上级 a37364f5
import paho.mqtt.client as mqtt
import logging
import threading
import time
from queue import Queue
from collections import defaultdict
# 配置日志输出到控制台
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s',
handlers=[logging.StreamHandler()]
)
# 全局配置
THREAD_COUNT = 5 # 线程数量
message_queue = Queue() # 消息队列
message_counter = defaultdict(int) # 消息计数器
message_details = defaultdict(list) # 消息详细记录
class MessageStats:
def __init__(self):
self.total_count = 0
self.last_received = None
self.first_received = None
# 全局消息统计
global_stats = MessageStats()
def print_banner(title):
"""打印分隔横幅"""
banner = f"\n=== {title} ===\n"
print(banner)
def test_progress():
"""测试进度显示"""
print_banner("系统测试")
for i in range(1, 6):
time.sleep(0.5)
logging.info(f"系统测试中... {i}/5")
print_banner("测试完成")
def on_connect(client, userdata, flags, rc):
"""MQTT连接回调"""
if rc == 0:
logging.info("MQTT连接成功")
client.subscribe("/androidPanel/#") # 订阅所有相关主题
else:
logging.error(f"MQTT连接失败,错误码: {rc}")
def on_message(client, userdata, msg):
"""MQTT消息回调"""
try:
payload = msg.payload.decode()
logging.info(f"收到原始消息 - 主题: {msg.topic}")
message_queue.put((msg.topic, payload))
except Exception as e:
logging.error(f"消息处理失败: {e}")
def worker_thread():
"""工作线程函数 - 只记录消息不进行其他操作"""
while True:
topic, payload = message_queue.get()
try:
# 记录消息统计
message_counter[topic] += 1
global_stats.total_count += 1
# 记录详细消息
timestamp = time.strftime('%Y-%m-%d %H:%M:%S')
message_details[topic].append({
'timestamp': timestamp,
'payload': payload
})
# 更新首次/最后接收时间
if global_stats.first_received is None:
global_stats.first_received = timestamp
global_stats.last_received = timestamp
# 打印消息摘要
logging.info(
f"消息记录 - 主题: {topic} | "
f"次数: {message_counter[topic]} | "
f"时间: {timestamp}"
)
# 定期打印统计摘要
if global_stats.total_count % 10 == 0:
print_banner("统计摘要")
logging.info(f"运行时间: {time.strftime('%H:%M:%S', time.gmtime(time.time() - start_time))}")
logging.info(f"总消息数: {global_stats.total_count}")
for topic, count in message_counter.items():
logging.info(f"主题 '{topic}': {count}次")
except Exception as e:
logging.error(f"消息记录失败: {e}")
finally:
message_queue.task_done()
if __name__ == "__main__":
start_time = time.time()
print_banner("MQTT消息监控程序启动")
logging.info(f"启动时间: {time.strftime('%Y-%m-%d %H:%M:%S')}")
logging.info(f"工作线程数: {THREAD_COUNT}")
# 测试系统功能
test_progress()
# 启动工作线程池
for i in range(THREAD_COUNT):
t = threading.Thread(
target=worker_thread,
name=f"Worker-{i + 1}",
daemon=True
)
t.start()
logging.info(f"已启动工作线程 {i + 1}/{THREAD_COUNT}")
# 创建MQTT客户端
client = mqtt.Client()
client.username_pw_set("mqtt@cmdb", "mqtt@webpassw0RD")
client.on_connect = on_connect
client.on_message = on_message
try:
# 连接MQTT服务器
client.connect("192.168.5.229", 1883)
logging.info("MQTT客户端已启动,等待消息...")
# 保持运行
client.loop_forever()
except KeyboardInterrupt:
print_banner("程序终止")
logging.info("最终统计:")
logging.info(f"总运行时间: {time.strftime('%H:%M:%S', time.gmtime(time.time() - start_time))}")
logging.info(f"总接收消息数: {global_stats.total_count}")
for topic, count in message_counter.items():
logging.info(f"主题 '{topic}': {count}次")
except Exception as e:
logging.error(f"程序发生错误: {e}")
finally:
client.disconnect()
logging.info("MQTT客户端已断开连接")
\ No newline at end of file
...@@ -25,45 +25,113 @@ THREAD_COUNT = 110 # 减少线程数量便于观察进度 ...@@ -25,45 +25,113 @@ THREAD_COUNT = 110 # 减少线程数量便于观察进度
DOWNLOAD_DIR = "downloads" DOWNLOAD_DIR = "downloads"
os.makedirs(DOWNLOAD_DIR, exist_ok=True) os.makedirs(DOWNLOAD_DIR, exist_ok=True)
def test_progress(): def test_progress():
"""测试进度显示""" """
测试进度显示函数
该函数用于模拟和测试进度显示功能,通过循环打印从10%到100%的进度信息,
每次间隔0.2秒,用于验证进度显示功能是否正常工作。
参数:
返回值:
"""
logging.info("\n=== 进度测试 ===") logging.info("\n=== 进度测试 ===")
# 模拟进度从10%到100%的变化过程
for i in range(1, 11): for i in range(1, 11):
time.sleep(0.2) time.sleep(0.2)
logging.info(f"测试进度: {i * 10}%") logging.info(f"测试进度: {i * 10}%")
logging.info("=== 测试完成 ===\n") logging.info("=== 测试完成 ===\n")
def on_connect(client, userdata, flags, rc): def on_connect(client, userdata, flags, rc):
"""
MQTT连接成功回调函数
当客户端成功连接到MQTT代理时触发该回调函数。
Args:
client: MQTT客户端实例
- 用于执行MQTT相关操作(如订阅主题)
userdata: 用户自定义数据
- 通常为初始化时传入的用户数据
flags: 连接标志
- 代理返回的连接标志信息
rc: 连接结果码
- 0: 连接成功
- 其他值: 连接失败(具体错误码参考MQTT协议)
Returns:
None
"""
logging.info("MQTT连接成功") logging.info("MQTT连接成功")
# 连接成功后立即订阅指定主题
client.subscribe("/androidPanel/") client.subscribe("/androidPanel/")
def on_message(client, userdata, msg): def on_message(client, userdata, msg):
"""
MQTT消息接收回调函数,处理接收到的消息并加入消息队列
Args:
client: MQTT客户端实例
userdata: 用户自定义数据,通常由Client()设置
msg: MQTT消息对象,包含topic、payload等信息
Returns:
None: 无返回值
"""
try: try:
# 解析JSON格式的消息内容并放入消息队列
payload = json.loads(msg.payload.decode()) payload = json.loads(msg.payload.decode())
message_queue.put(payload) message_queue.put(payload)
logging.info(f"消息已加入队列: UDID={payload['udid'][0]}") logging.info(f"消息已加入队列: UDID={payload['udid'][0]}")
except Exception as e: except Exception as e:
# 捕获并记录消息处理过程中的任何异常
logging.error(f"消息解析失败: {e}") logging.error(f"消息解析失败: {e}")
def download_file(url, save_path, desc="Downloading", max_retries=3, retry_delay=5): def download_file(url, save_path, desc="Downloading", max_retries=3, retry_delay=5):
"""增强版文件下载,支持断点续传和重试""" """
增强版文件下载函数,支持断点续传和自动重试机制
参数:
url (str): 要下载的文件URL地址
save_path (str): 本地保存路径
desc (str): 下载进度描述文本,默认为"Downloading"
max_retries (int): 最大重试次数,默认为3
retry_delay (int): 重试间隔时间(秒),默认为5
返回值:
bool: 下载成功返回True,失败返回False
功能说明:
1. 支持断点续传,自动检测已下载部分并继续下载
2. 自动验证文件完整性
3. 提供详细的下载进度和速度信息
4. 支持失败自动重试机制
"""
for attempt in range(max_retries): for attempt in range(max_retries):
try: try:
# 断点续传处理 # 断点续传处理:检查本地是否存在部分下载文件
file_size = 0 file_size = 0
if os.path.exists(save_path): if os.path.exists(save_path):
file_size = os.path.getsize(save_path) file_size = os.path.getsize(save_path)
logging.info(f"发现未完成下载文件,尝试续传: {save_path} (已下载: {file_size / 1024 / 1024:.2f}MB)") logging.info(f"发现未完成下载文件,尝试续传: {save_path} (已下载: {file_size / 1024 / 1024:.2f}MB)")
# 设置HTTP请求头,支持断点续传
headers = {'Range': f'bytes={file_size}-'} if file_size else {} headers = {'Range': f'bytes={file_size}-'} if file_size else {}
# 打印调试信息 # 打印下载基本信息
logging.info(f"\n开始下载: {url}") logging.info(f"\n开始下载: {url}")
logging.info(f"保存路径: {os.path.abspath(save_path)}") logging.info(f"保存路径: {os.path.abspath(save_path)}")
logging.info(f"已下载: {file_size / 1024 / 1024:.2f}MB") logging.info(f"已下载: {file_size / 1024 / 1024:.2f}MB")
# 发起HTTP请求并处理响应
with requests.get( with requests.get(
url, url,
headers=headers, headers=headers,
...@@ -73,7 +141,7 @@ def download_file(url, save_path, desc="Downloading", max_retries=3, retry_delay ...@@ -73,7 +141,7 @@ def download_file(url, save_path, desc="Downloading", max_retries=3, retry_delay
) as r: ) as r:
r.raise_for_status() r.raise_for_status()
# 获取文件总大小 # 计算文件总大小(包括已下载部分)
total_size = int(r.headers.get('content-length', 0)) + file_size total_size = int(r.headers.get('content-length', 0)) + file_size
if total_size == 0: if total_size == 0:
raise ValueError("无法获取文件总大小") raise ValueError("无法获取文件总大小")
...@@ -81,6 +149,7 @@ def download_file(url, save_path, desc="Downloading", max_retries=3, retry_delay ...@@ -81,6 +149,7 @@ def download_file(url, save_path, desc="Downloading", max_retries=3, retry_delay
logging.info(f"总大小: {total_size / 1024 / 1024:.2f}MB") logging.info(f"总大小: {total_size / 1024 / 1024:.2f}MB")
logging.info(f"创建时间: {time.strftime('%Y-%m-%d %H:%M:%S')}") logging.info(f"创建时间: {time.strftime('%Y-%m-%d %H:%M:%S')}")
# 设置文件写入模式(追加或新建)
mode = 'ab' if file_size else 'wb' mode = 'ab' if file_size else 'wb'
downloaded = file_size downloaded = file_size
last_update = time.time() last_update = time.time()
...@@ -93,6 +162,7 @@ def download_file(url, save_path, desc="Downloading", max_retries=3, retry_delay ...@@ -93,6 +162,7 @@ def download_file(url, save_path, desc="Downloading", max_retries=3, retry_delay
os.fsync(f.fileno()) os.fsync(f.fileno())
logging.info(f"文件写入测试成功,当前大小: {os.path.getsize(save_path)} bytes") logging.info(f"文件写入测试成功,当前大小: {os.path.getsize(save_path)} bytes")
# 分块下载并写入文件
for chunk in r.iter_content(chunk_size=8192): for chunk in r.iter_content(chunk_size=8192):
if chunk: if chunk:
# 写入文件并立即同步到磁盘 # 写入文件并立即同步到磁盘
...@@ -104,17 +174,18 @@ def download_file(url, save_path, desc="Downloading", max_retries=3, retry_delay ...@@ -104,17 +174,18 @@ def download_file(url, save_path, desc="Downloading", max_retries=3, retry_delay
# 实时打印文件状态 # 实时打印文件状态
current_size = os.path.getsize(save_path) current_size = os.path.getsize(save_path)
logging.info(f"\r当前文件大小: {current_size} bytes ({current_size / 1024 / 1024:.2f}MB)", end="", logging.info(f"\r当前文件大小: {current_size} bytes ({current_size / 1024 / 1024:.2f}MB)",
end="",
flush=True) flush=True)
# 进度显示 # 进度显示(每0.1秒更新一次)
if time.time() - last_update >= 0.1: if time.time() - last_update >= 0.1:
percent = (downloaded / total_size) * 100 percent = (downloaded / total_size) * 100
speed = (downloaded - file_size) / (time.time() - last_update) / 1024 speed = (downloaded - file_size) / (time.time() - last_update) / 1024
logging.info(f"\n{desc} 进度: {percent:.1f}% | 速度: {speed:.1f}KB/s") logging.info(f"\n{desc} 进度: {percent:.1f}% | 速度: {speed:.1f}KB/s")
last_update = time.time() last_update = time.time()
# 最终验证 # 最终文件完整性验证
final_size = os.path.getsize(save_path) final_size = os.path.getsize(save_path)
logging.info(f"\n下载完成! 最终文件大小: {final_size} bytes") logging.info(f"\n下载完成! 最终文件大小: {final_size} bytes")
if final_size != total_size: if final_size != total_size:
...@@ -123,6 +194,7 @@ def download_file(url, save_path, desc="Downloading", max_retries=3, retry_delay ...@@ -123,6 +194,7 @@ def download_file(url, save_path, desc="Downloading", max_retries=3, retry_delay
return True return True
except Exception as e: except Exception as e:
# 异常处理:记录错误并等待重试
logging.exception(f"下载失败 (尝试 {attempt + 1}/{max_retries}): {str(e)}") logging.exception(f"下载失败 (尝试 {attempt + 1}/{max_retries}): {str(e)}")
if attempt < max_retries - 1: if attempt < max_retries - 1:
time.sleep(retry_delay * (attempt + 1)) time.sleep(retry_delay * (attempt + 1))
...@@ -131,18 +203,35 @@ def download_file(url, save_path, desc="Downloading", max_retries=3, retry_delay ...@@ -131,18 +203,35 @@ def download_file(url, save_path, desc="Downloading", max_retries=3, retry_delay
def worker_thread(): def worker_thread():
"""工作线程函数""" """
工作线程函数,用于从消息队列中获取任务并处理下载请求
功能描述:
- 从消息队列中获取消息载荷(payload)
- 构建下载请求的URL和请求头
- 创建会话并设置重试机制
- 下载文件并显示进度信息
- 处理各种异常情况并记录日志
处理流程:
1. 从消息队列获取任务
2. 提取授权信息和设备ID
3. 配置下载请求参数
4. 创建带有重试机制的HTTP会话
5. 执行下载并保存文件
6. 处理异常和重试逻辑
"""
while True: while True:
payload = message_queue.get() payload = message_queue.get()
try: try:
# 从MQTT消息获取动态参数 # 从消息载荷中提取必要信息
actual_auth = payload["headers"]["Authorization"] actual_auth = payload["headers"]["Authorization"]
udid = payload["udid"][0] udid = payload["udid"][0]
# 构建apk的请求参数 # 配置下载pak请求URL和请求头
# url = "http://192.168.5.229:8999/androidPanel/pack/download?id=30"
# 构建pak的请求参数
url = "http://192.168.5.229:8999/androidPanel/pack/download?id=29" url = "http://192.168.5.229:8999/androidPanel/pack/download?id=29"
# 配置下载apk请求URL和请求头
# url = "http://192.168.5.229:8999/androidPanel/pack/download?id=30"
headers = { headers = {
"Content-Type": "application/x-www-form-urlencoded", "Content-Type": "application/x-www-form-urlencoded",
...@@ -154,43 +243,43 @@ def worker_thread(): ...@@ -154,43 +243,43 @@ def worker_thread():
'Connection': 'keep-alive' 'Connection': 'keep-alive'
} }
# 确定保存路径 # 准备文件保存路径
file_name = f"{udid}_downloaded_file.bin" file_name = f"{udid}_downloaded_file.bin"
save_path = os.path.abspath(os.path.join(DOWNLOAD_DIR, file_name)) save_path = os.path.abspath(os.path.join(DOWNLOAD_DIR, file_name))
# 创建会话并设置重试机制 # 创建带有重试机制的HTTP会话
session = requests.Session() session = requests.Session()
adapter = requests.adapters.HTTPAdapter( adapter = requests.adapters.HTTPAdapter(
max_retries=3, max_retries=3,
pool_connections=20, # 减少连接池大小 pool_connections=20,
pool_maxsize=20, pool_maxsize=20,
pool_block=True pool_block=True
) )
session.mount('http://', adapter) session.mount('http://', adapter)
session.mount('https://', adapter) session.mount('https://', adapter)
# 下载文件(带重试机制)
max_retries = 3 max_retries = 3
for attempt in range(max_retries): for attempt in range(max_retries):
try: try:
# 增加更长的超时时间 # 执行下载请求
with session.post( with session.post(
url, url,
headers=headers, headers=headers,
stream=True, stream=True,
verify=False, verify=False,
timeout=(30, 300), # 连接超时30秒,读取超时300秒 timeout=(30, 300),
) as response: ) as response:
response.raise_for_status() response.raise_for_status()
# 获取文件总大小 # 处理文件下载
total_size = int(response.headers.get('content-length', 0)) total_size = int(response.headers.get('content-length', 0))
if total_size == 0: if total_size == 0:
raise ValueError("无法获取文件总大小") raise ValueError("无法获取文件总大小")
# 创建下载目录
os.makedirs(DOWNLOAD_DIR, exist_ok=True) os.makedirs(DOWNLOAD_DIR, exist_ok=True)
# 写入文件 # 下载文件并显示进度
downloaded = 0 downloaded = 0
start_time = time.time() start_time = time.time()
...@@ -199,8 +288,6 @@ def worker_thread(): ...@@ -199,8 +288,6 @@ def worker_thread():
if chunk: if chunk:
f.write(chunk) f.write(chunk)
downloaded += len(chunk) downloaded += len(chunk)
# 每1MB打印一次进度
if downloaded % (1024 * 1024) == 0: if downloaded % (1024 * 1024) == 0:
speed = downloaded / (time.time() - start_time) / 1024 speed = downloaded / (time.time() - start_time) / 1024
logging.info( logging.info(
...@@ -213,16 +300,19 @@ def worker_thread(): ...@@ -213,16 +300,19 @@ def worker_thread():
break break
except (requests.exceptions.RequestException, ValueError) as e: except (requests.exceptions.RequestException, ValueError) as e:
# 处理下载失败和重试逻辑
if attempt == max_retries - 1: if attempt == max_retries - 1:
logging.error(f"{udid} 下载最终失败: {str(e)}") logging.error(f"{udid} 下载最终失败: {str(e)}")
raise raise
wait_time = (attempt + 1) * 10 # 增加重试等待时间 wait_time = (attempt + 1) * 10
logging.warning(f"{udid} 下载失败,{wait_time}秒后重试... ({attempt + 1}/{max_retries})") logging.warning(f"{udid} 下载失败,{wait_time}秒后重试... ({attempt + 1}/{max_retries})")
time.sleep(wait_time) time.sleep(wait_time)
except Exception as e: except Exception as e:
# 处理线程中的其他异常
logging.exception(f"{udid} 线程处理异常: {str(e)}") logging.exception(f"{udid} 线程处理异常: {str(e)}")
finally: finally:
# 标记任务完成
message_queue.task_done() message_queue.task_done()
......
...@@ -37,18 +37,52 @@ csv_file_path = os.path.join(current_dir, '../测试数据/预定系统-门口 ...@@ -37,18 +37,52 @@ csv_file_path = os.path.join(current_dir, '../测试数据/预定系统-门口
class StableMQTTClient: class StableMQTTClient:
def __init__(self, broker_address, port, username, password, client_id): def __init__(self, broker_address, port, username, password, client_id):
self.broker_address = broker_address """
self.port = port 初始化MQTT客户端实例
self.username = username
self.password = password 参数:
self.client_id = client_id broker_address (str): MQTT代理服务器的地址/IP
port (int): MQTT代理服务器的端口号
username (str): 连接代理服务器的用户名
password (str): 连接代理服务器的密码
client_id (str): 客户端的唯一标识符
功能:
1. 保存连接参数
2. 初始化客户端对象为None
3. 自动尝试连接代理服务器
"""
# 保存MQTT连接参数
self.broker_address = broker_address # 代理服务器地址
self.port = port # 端口号
self.username = username # 用户名
self.password = password # 密码
self.client_id = client_id # 客户端ID
# 初始化MQTT客户端对象(将在connect方法中实例化)
self.client = None self.client = None
# 自动尝试连接代理服务器
self.connect() self.connect()
def connect(self): def connect(self):
"""
尝试连接到MQTT broker,最多重试3次。
每次连接失败后会等待递增的时间后重试(5秒、10秒、15秒)。
如果所有尝试都失败,则抛出最后的异常并记录错误日志。
连接成功时会记录成功日志并返回True。
Returns:
bool: 连接成功返回True,否则抛出异常。
Raises:
Exception: 当所有重试尝试都失败时,抛出最后一次连接尝试的异常。
"""
max_retries = 3 max_retries = 3
for attempt in range(max_retries): for attempt in range(max_retries):
try: try:
# 创建MQTT客户端并尝试连接
self.client = Mqtt(self.broker_address, self.port, self.client = Mqtt(self.broker_address, self.port,
self.username, self.password, self.client_id) self.username, self.password, self.client_id)
self.client.set_message_type("json") self.client.set_message_type("json")
...@@ -56,17 +90,34 @@ class StableMQTTClient: ...@@ -56,17 +90,34 @@ class StableMQTTClient:
logging.info(f"连接成功,Client ID: {self.client_id}") logging.info(f"连接成功,Client ID: {self.client_id}")
return True return True
except Exception as e: except Exception as e:
# 最后一次尝试失败时直接抛出异常
if attempt == max_retries - 1: if attempt == max_retries - 1:
logging.error(f"连接失败 (尝试 {attempt + 1}/{max_retries}): {str(e)}") logging.error(f"连接失败 (尝试 {attempt + 1}/{max_retries}): {str(e)}")
raise raise
# 非最后一次失败时等待递增时间后重试
wait_time = (attempt + 1) * 5 wait_time = (attempt + 1) * 5
logging.warning(f"连接失败,{wait_time}秒后重试... ({attempt + 1}/{max_retries})") logging.warning(f"连接失败,{wait_time}秒后重试... ({attempt + 1}/{max_retries})")
time.sleep(wait_time) time.sleep(wait_time)
def publish(self, topic, message): def publish(self, topic, message):
"""
发布消息到指定主题。
如果发布失败,将自动尝试重新连接并重试一次发布操作。
参数:
topic (str): 要发布消息的主题名称
message (str): 要发布的消息内容
异常:
如果重试后仍然失败,将通过logging记录错误但不会抛出异常
"""
try: try:
# 尝试发布消息
self.client.publish(topic, message) self.client.publish(topic, message)
except Exception as e: except Exception as e:
# 发布失败时记录错误并尝试重新连接后重试
logging.error(f"发布消息失败: {str(e)},尝试重新连接...") logging.error(f"发布消息失败: {str(e)},尝试重新连接...")
self.connect() self.connect()
self.client.publish(topic, message) # 重试一次 self.client.publish(topic, message) # 重试一次
...@@ -74,9 +125,21 @@ class StableMQTTClient: ...@@ -74,9 +125,21 @@ class StableMQTTClient:
# 工作线程函数 # 工作线程函数
def worker(mqtt_client, config_queue, interval): def worker(mqtt_client, config_queue, interval):
"""MQTT消息发布工作线程
持续从配置队列中获取配置信息,构建MQTT消息并发布到指定主题。
该线程会循环运行直到被外部中断。
Args:
mqtt_client: 已连接的MQTT客户端实例,用于发布消息
config_queue: 包含配置信息的队列,每个配置项应包含topic等必要字段
interval: 每次消息发布后的间隔时间(秒)
"""
while True: while True:
# 从队列获取配置信息
config = config_queue.get() config = config_queue.get()
try: try:
# 构建并发布MQTT消息
topic = config["topic"] topic = config["topic"]
current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S") current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
message = Mqtt.build_message(config, current_time, topic) message = Mqtt.build_message(config, current_time, topic)
...@@ -85,9 +148,11 @@ def worker(mqtt_client, config_queue, interval): ...@@ -85,9 +148,11 @@ def worker(mqtt_client, config_queue, interval):
time.sleep(interval) time.sleep(interval)
except Exception as e: except Exception as e:
# 异常处理:记录错误日志并短暂等待
logging.error(f"线程 {threading.current_thread().name} 发送消息失败: {e}") logging.error(f"线程 {threading.current_thread().name} 发送消息失败: {e}")
time.sleep(5) # 出错后等待5秒 time.sleep(5) # 出错后等待5秒
finally: finally:
# 标记队列任务完成
config_queue.task_done() config_queue.task_done()
......
...@@ -72,7 +72,7 @@ def browser_init(login_type): ...@@ -72,7 +72,7 @@ def browser_init(login_type):
options.add_argument('--allow-insecure-localhost') options.add_argument('--allow-insecure-localhost')
# 使用webdriver_manager自动下载并管理chromedriver # 使用webdriver_manager自动下载并管理chromedriver
service = ChromeService(ChromeDriverManager().install()) # service = ChromeService(ChromeDriverManager().install())
# 使用备用的ChromeDriver下载源 # 使用备用的ChromeDriver下载源
# service = Service(ChromeDriverManager().install()) # service = Service(ChromeDriverManager().install())
# 手动指定ChromeDriver的路径 # 手动指定ChromeDriver的路径
...@@ -83,7 +83,7 @@ def browser_init(login_type): ...@@ -83,7 +83,7 @@ def browser_init(login_type):
# EDY电脑 # EDY电脑
# service = Service(r'C:\Users\EDY\AppData\Local\Programs\Python\Python310\Scripts\chromedriver.exe') # service = Service(r'C:\Users\EDY\AppData\Local\Programs\Python\Python310\Scripts\chromedriver.exe')
# 云电脑 # 云电脑
# service = Service(r'E:\Python\Scripts\chromedriver.exe') service = Service(r'E:\Python\Scripts\chromedriver.exe')
# 自动化虚拟机 # 自动化虚拟机
# service = Service(r'C:\Program Files\Python310\Scripts\chromedriver.exe') # service = Service(r'C:\Program Files\Python310\Scripts\chromedriver.exe')
# 尝试创建WebDriver实例并执行初始化操作 # 尝试创建WebDriver实例并执行初始化操作
......
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论