Appium2 uses python to operate the simulator installed in the wechat software automation, elements=driver.find_elements(By.CLASS_NAME, "android.widget.Button") 500 exception, Whether find_elements can be used normally

Environment

C:\Users\13320>appium
[Appium] Welcome to Appium v2.11.1
[Appium] The autodetected Appium home path: C:\Users\13320\.appium
[Appium] Attempting to load driver uiautomator2...
[Appium] Requiring driver at C:\Users\13320\.appium\node_modules\appium-uiautomator2-driver\build\index.js
[Appium] AndroidUiautomator2Driver has been successfully loaded in 2.347s
[Appium] Appium REST http interface listener started on http://0.0.0.0:4723
[Appium] You can provide the following URLs in your client code to connect to this server:
        http://192.168.88.1:4723/
        http://192.168.136.1:4723/
        http://192.168.66.85:4723/
        http://127.0.0.1:4723/ (only accessible from the same host)
[Appium] Available drivers:
[Appium]   - [email protected] (automationName 'UiAutomator2')
[Appium] Available plugins:
[Appium]   - [email protected]
[Appium]   - [email protected]
[Appium]   - [email protected]
[Appium]   - [email protected]
[Appium] No plugins activated. Use the --use-plugins flag with names of plugins to activate

Current Behavior

There is no problem with the automatic operation in front of the program, only here there are always 500 exceptions, and there is no problem with loading.

# 查找所有android.widget.Button的text

      def find_elements_with_retry(driver, by, value, retries=3, delay=5):
          for attempt in range(retries):
              try:
                  elements = driver.find_elements(by, value)
                  if elements:
                      return elements
              except Exception as e:
                  logging.error(f"Error finding elements: {str(e)}")
              time.sleep(delay)
          return []

        elements = find_elements_with_retry(driver, By.CLASS_NAME, "android.widget.Button")

Expected Behavior

Error reported as follows:

[da50e1b9][HTTP] --> POST /session/da50e1b9-f1d3-43c0-9bca-5d6c52cc333e/elements {"using":"class name","value":"android.widget.Button"}
[da50e1b9][AndroidUiautomator2Driver@5d3b] Calling AppiumDriver.findElements() with args: ["class name","android.widget.Button","da50e1b9-f1d3-43c0-9bca-5d6c52cc333e"]
[da50e1b9][AndroidUiautomator2Driver@5d3b] Valid locator strategies for this request: xpath, id, class name, accessibility id, css selector, -android uiautomator
[da50e1b9][AndroidUiautomator2Driver@5d3b] Waiting up to 60000 ms for condition
[da50e1b9][AndroidUiautomator2Driver@5d3b] Matched '/elements' to command name 'findElements'
[da50e1b9][AndroidUiautomator2Driver@5d3b] Proxying [POST /elements] to [POST http://127.0.0.1:8203/session/f5381813-6ee5-4026-b7d0-e74f1eebd95a/elements] with body: {"strategy":"class name","selector":"android.widget.Button","context":"","multiple":true}
[a5a88ae7][HTTP] --> GET /session/a5a88ae7-dc12-4d55-a66b-bb46f6e36b8c/timeouts {}
[a5a88ae7][AppiumDriver@248e] Encountered internal error running command: NoSuchDriverError: A session is either terminated or not started
    at asyncHandler (D:\dev\nvm\v22.2.0\node_modules\appium\node_modules\@appium\base-driver\lib\protocol\protocol.js:309:15)
    at D:\dev\nvm\v22.2.0\node_modules\appium\node_modules\@appium\base-driver\lib\protocol\protocol.js:512:15
    at Layer.handle [as handle_request] (D:\dev\nvm\v22.2.0\node_modules\appium\node_modules\express\lib\router\layer.js:95:5)
    at next (D:\dev\nvm\v22.2.0\node_modules\appium\node_modules\express\lib\router\route.js:149:13)
    at Route.dispatch (D:\dev\nvm\v22.2.0\node_modules\appium\node_modules\express\lib\router\route.js:119:3)
    at Layer.handle [as handle_request] (D:\dev\nvm\v22.2.0\node_modules\appium\node_modules\express\lib\router\layer.js:95:5)
    at D:\dev\nvm\v22.2.0\node_modules\appium\node_modules\express\lib\router\index.js:284:15
    at param (D:\dev\nvm\v22.2.0\node_modules\appium\node_modules\express\lib\router\index.js:365:14)
    at param (D:\dev\nvm\v22.2.0\node_modules\appium\node_modules\express\lib\router\index.js:376:14)
    at Function.process_params (D:\dev\nvm\v22.2.0\node_modules\appium\node_modules\express\lib\router\index.js:421:3)
    at next (D:\dev\nvm\v22.2.0\node_modules\appium\node_modules\express\lib\router\index.js:280:10)
    at logger (D:\dev\nvm\v22.2.0\node_modules\appium\node_modules\morgan\index.js:144:5)
    at Layer.handle [as handle_request] (D:\dev\nvm\v22.2.0\node_modules\appium\node_modules\express\lib\router\layer.js:95:5)
    at trim_prefix (D:\dev\nvm\v22.2.0\node_modules\appium\node_modules\express\lib\router\index.js:328:13)
    at D:\dev\nvm\v22.2.0\node_modules\appium\node_modules\express\lib\router\index.js:286:9
    at Function.process_params (D:\dev\nvm\v22.2.0\node_modules\appium\node_modules\express\lib\router\index.js:346:12)
    at next (D:\dev\nvm\v22.2.0\node_modules\appium\node_modules\express\lib\router\index.js:280:10)
    at jsonParser (D:\dev\nvm\v22.2.0\node_modules\appium\node_modules\body-parser\lib\types\json.js:113:7)
    at Layer.handle [as handle_request] (D:\dev\nvm\v22.2.0\node_modules\appium\node_modules\express\lib\router\layer.js:95:5)
    at trim_prefix (D:\dev\nvm\v22.2.0\node_modules\appium\node_modules\express\lib\router\index.js:328:13)
    at D:\dev\nvm\v22.2.0\node_modules\appium\node_modules\express\lib\router\index.js:286:9
    at Function.process_params (D:\dev\nvm\v22.2.0\node_modules\appium\node_modules\express\lib\router\index.js:346:12)
[a5a88ae7][HTTP] <-- GET /session/a5a88ae7-dc12-4d55-a66b-bb46f6e36b8c/timeouts 404 2 ms - 2835
[da50e1b9][AndroidUiautomator2Driver@5d3b] Got response with status 500: {"sessionId":"f5381813-6ee5-4026-b7d0-e74f1eebd95a","value":{"error":"unknown error","message":"Timed out after 15527ms waiting for the root AccessibilityNodeInfo in the active window. Make sure the active window is not constantly hogging the main UI thread (e.g. the application is being idle long enough), so the accessibility manager could do its work","stacktrace":"io.appium.uiautomator2.common.exceptions.UiAutomator2Exception: Timed out after 15527ms waiting for the root AccessibilityNodeInfo in the active window. Make sure the active window is not constantly hogging the main UI thread (e.g. the application is being idle long enough), so the accessibility manager could do its work\n\tat io.appium.uiautomator2.utils.AXWindowHelpers.getActiveWindowRoot(AXWindowHelpers.java:82)\n\tat io.appium.uiautomator2.utils.AXWindowHelpers.getCachedWindowRoots(AXWindowHelpers.java:148)\n\tat io.appium.uiautomator2.model.internal.CustomUiDevice.findObjects(CustomUiDevice.java:193)\n\tat io.appium.uiautomator2.utils.Ele...
[da50e1b9][W3C] Matched W3C error code 'unknown error' to UnknownError
[da50e1b9][AndroidUiautomator2Driver@5d3b] Encountered internal error running command: An unknown server-side error occurred while processing the command. Original error: Timed out after 15527ms waiting for the root AccessibilityNodeInfo in the active window. Make sure the active window is not constantly hogging the main UI thread (e.g. the application is being idle long enough), so the accessibility manager could do its work
io.appium.uiautomator2.common.exceptions.UiAutomator2Exception: Timed out after 15527ms waiting for the root AccessibilityNodeInfo in the active window. Make sure the active window is not constantly hogging the main UI thread (e.g. the application is being idle long enough), so the accessibility manager could do its work
        at io.appium.uiautomator2.utils.AXWindowHelpers.getActiveWindowRoot(AXWindowHelpers.java:82)
        at io.appium.uiautomator2.utils.AXWindowHelpers.getCachedWindowRoots(AXWindowHelpers.java:148)
        at io.appium.uiautomator2.model.internal.CustomUiDevice.findObjects(CustomUiDevice.java:193)
        at io.appium.uiautomator2.utils.ElementLocationHelpers.findElements(ElementLocationHelpers.java:201)
        at io.appium.uiautomator2.handler.FindElements.safeHandle(FindElements.java:69)
        at io.appium.uiautomator2.handler.request.SafeRequestHandler.handle(SafeRequestHandler.java:59)
        at io.appium.uiautomator2.server.AppiumServlet.handleRequest(AppiumServlet.java:259)
        at io.appium.uiautomator2.server.AppiumServlet.handleHttpRequest(AppiumServlet.java:253)
        at io.appium.uiautomator2.http.ServerHandler.channelRead(ServerHandler.java:77)
        at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:366)
        at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:352)
        at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:345)
        at io.netty.handler.codec.MessageToMessageDecoder.channelRead(MessageToMessageDecoder.java:102)
        at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:366)
        at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:352)
        at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:345)
        at io.netty.channel.CombinedChannelDuplexHandler$DelegatingChannelHandlerContext.fireChannelRead(CombinedChannelDuplexHandler.java:435)
        at io.netty.handler.codec.ByteToMessageDecoder.fireChannelRead(ByteToMessageDecoder.java:293)
        at io.netty.handler.codec.ByteToMessageDecoder.channelRead(ByteToMessageDecoder.java:267)
        at io.netty.channel.CombinedChannelDuplexHandler.channelRead(CombinedChannelDuplexHandler.java:250)
        at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:366)
        at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:352)
        at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:345)
        at io.netty.handler.timeout.IdleStateHandler.channelRead(IdleStateHandler.java:266)
        at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:366)
        at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:352)
        at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:345)
        at io.netty.channel.DefaultChannelPipeline$HeadContext.channelRead(DefaultChannelPipeline.java:1294)
        at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:366)
        at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:352)
        at io.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:911)
        at io.netty.channel.nio.AbstractNioByteChannel$NioByteUnsafe.read(AbstractNioByteChannel.java:131)
        at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:611)
        at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:552)
        at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:466)
        at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:438)
        at io.netty.util.concurrent.SingleThreadEventExecutor$2.run(SingleThreadEventExecutor.java:140)
        at io.netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:144)
        at java.lang.Thread.run(Thread.java:764)

[da50e1b9][HTTP] <-- POST /session/da50e1b9-f1d3-43c0-9bca-5d6c52cc333e/elements 500 15544 ms - 4613

###测试程序如下

import os
import time
import logging
import yaml
import pandas as pd
import subprocess
from appium import webdriver
from selenium.webdriver.common.by import By
from appium.webdriver.appium_connection import AppiumConnection
from appium.options.android import UiAutomator2Options

# 创建日志文件夹
log_folder = 'log'
if not os.path.exists(log_folder):
    os.makedirs(log_folder)

# 配置日志记录
logging.basicConfig(
    filename=os.path.join(log_folder, 'err.log'),
    level=logging.ERROR,
    format='%(asctime)s - %(levelname)s - %(message)s'
)

# 读取配置文件
with open('resources/config.yaml', 'r', encoding='utf-8') as config_file:
    config_data = yaml.safe_load(config_file)


# 自定义Appium连接类
class CustomAppiumConnection(AppiumConnection):
    pass


# 重启微信应用
def restart_wechat():
    print("重启微信应用...")
    subprocess.run(["adb", "shell", "am", "force-stop", "com.tencent.mm"])  # 停止微信
    time.sleep(5)
    subprocess.run(["adb", "shell", "am", "start", "-n", "com.tencent.mm/.ui.LauncherUI"])  # 启动微信
    time.sleep(20)  # 等待微信完全启动


# 创建自定义Appium连接
custom_executor = CustomAppiumConnection(remote_server_addr=config_data["appium_server"])

# 创建Appium选项
options = UiAutomator2Options().load_capabilities(config_data)

# 重启微信应用
restart_wechat()

# 创建Appium驱动程序
driver = webdriver.Remote(command_executor=custom_executor, options=options)

# 设置缺省等待时间
driver.implicitly_wait(config_data["implicitlyWait"])
# 更新设置
driver.update_settings({"enforceXPath1": True})

# 加载待查询文件数据
account_file = rf"resources/关键词.txt"
search_keywords = []
with open(account_file, 'r', encoding='utf-8') as file:
    lines = file.read().splitlines()
    for line in lines:
        cleaned_line = line.strip()
        if cleaned_line:
            if cleaned_line not in search_keywords:
                search_keywords.append(cleaned_line)

# 加载地区信息
domain_file = rf"resources/地市县级.txt"
with open(domain_file, 'r', encoding='utf-8') as file:
    domain_list = [item for line in file for item in line.strip().split('、')]

# 创建结果目录
if not os.path.exists('公众号搜索results'):
    os.makedirs('公众号搜索results')

# 结果列表
all_texts = []

# 点击搜索按钮
search_box = driver.find_element(By.XPATH, "//android.widget.RelativeLayout[@content-desc='搜索']")
search_box.click()


def find_elements_with_retry(driver, by, value, retries=3, delay=5):
    for attempt in range(retries):
        try:
            elements = driver.find_elements(by, value)
            if elements:
                return elements
        except Exception as e:
            logging.error(f"Error finding elements: {str(e)}")
        time.sleep(delay)
    return []


try:
    for i, keyword in enumerate(search_keywords, start=1):
        print(f"查询关键词: {keyword}")

        search_input = driver.find_element(By.XPATH, "//android.widget.EditText[@text='搜索']")
        search_input.send_keys(keyword)

        # 点击搜索结果中的第一个
        search_result = driver.find_element(By.XPATH, f"//android.widget.TextView[contains(@text, '{keyword}')]")
        search_result.click()

        # 点击屏幕上的坐标,使用 tap 方法点击公众号坐标
        driver.tap([(515, 206)])

        # 页面下滑,查找所有按钮的text
        elements = find_elements_with_retry(driver, By.CLASS_NAME, "android.widget.Button")
        for element in elements:
            text = element.text
            print("Button text:", text)
            all_texts.append(text)
    # driver.swipe(500, 1500, 500, 900)  # 下滑动作
    # time.sleep(2)

except Exception as e:
    logging.error(f"发生错误: {str(e)}")
finally:
    # 关闭WebDriver实例
    driver.quit()

# 处理数据
results = []
for text in all_texts:
    for domain in domain_list:
        if domain in text:
            parts = text.split(" ")
            if len(parts) >= 2:
                name = parts[0]
                content = " ".join(parts[1:])
                results.append({
                    '地区': domain,
                    '公众号名称': name,
                    '内容': content
                })
            break

# 写入结果到Excel文件
df = pd.DataFrame(results)
df.to_excel('公众号搜索results/results.xlsx', index=False)