Commit 378fd3f7 authored by haohao's avatar haohao

Initial commit

parents
# 默认忽略的文件
/shelf/
/workspace.xml
# 基于编辑器的 HTTP 客户端请求
/httpRequests/
# Datasource local storage ignored files
/dataSources/
/dataSources.local.xml
<?xml version="1.0" encoding="UTF-8"?>
<module type="PYTHON_MODULE" version="4">
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$" />
<orderEntry type="jdk" jdkName="xhs" jdkType="Python SDK" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
<component name="PyDocumentationSettings">
<option name="format" value="PLAIN" />
<option name="myDocStringFormat" value="Plain" />
</component>
</module>
\ No newline at end of file
<component name="InspectionProjectProfileManager">
<settings>
<option name="USE_PROJECT_PROFILE" value="false" />
<version value="1.0" />
</settings>
</component>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Black">
<option name="sdkName" value="Python 3.8" />
</component>
<component name="ProjectRootManager" version="2" project-jdk-name="xhs" project-jdk-type="Python SDK" />
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/auto_xhs.iml" filepath="$PROJECT_DIR$/.idea/auto_xhs.iml" />
</modules>
</component>
</project>
\ No newline at end of file
<?xml version='1.0' encoding='UTF-8' standalone='yes' ?>
<hierarchy rotation="0">
<node index="0" text="" resource-id="" class="android.widget.LinearLayout" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[0,2118][1080,2248]" drawing-order="0" hint="">
<node index="0" text="" resource-id="com.android.systemui:id/rot0" class="android.widget.FrameLayout" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[0,2118][1080,2248]" drawing-order="1" hint="">
<node index="0" text="" resource-id="com.android.systemui:id/deadzone" class="android.view.View" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[0,2118][1080,2248]" drawing-order="3" hint="" />
<node index="1" text="" resource-id="com.android.systemui:id/nav_buttons" class="android.widget.LinearLayout" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[0,2118][1080,2248]" drawing-order="1" hint="">
<node index="0" text="" resource-id="com.android.systemui:id/start_padding" class="android.widget.FrameLayout" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[0,2118][233,2248]" drawing-order="1" hint="" />
<node index="1" text="" resource-id="com.android.systemui:id/recent_apps" class="android.widget.ImageView" package="com.android.systemui" content-desc="概览" checkable="false" checked="false" clickable="true" enabled="true" focusable="true" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[233,2118][398,2248]" drawing-order="2" hint="" />
<node index="2" text="" resource-id="com.android.systemui:id/home" class="android.widget.ImageView" package="com.android.systemui" content-desc="主屏幕" checkable="false" checked="false" clickable="true" enabled="true" focusable="true" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[457,2118][622,2248]" drawing-order="4" hint="" />
<node index="3" text="" resource-id="com.android.systemui:id/back" class="android.widget.ImageView" package="com.android.systemui" content-desc="返回" checkable="false" checked="false" clickable="true" enabled="true" focusable="true" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[681,2118][846,2248]" drawing-order="6" hint="" />
<node index="4" text="" resource-id="com.android.systemui:id/side_padding" class="android.widget.FrameLayout" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[846,2118][1080,2248]" drawing-order="7" hint="" />
</node>
</node>
</node>
<node index="0" text="" resource-id="" class="android.widget.FrameLayout" package="com.xingin.xhs" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[0,0][1080,2248]" drawing-order="0" hint="">
<node index="0" text="" resource-id="com.xingin.xhs:id/0_resource_name_obfuscated" class="android.widget.FrameLayout" package="com.xingin.xhs" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[0,0][1080,2248]" drawing-order="1" hint="">
<node index="0" text="" resource-id="" class="android.widget.LinearLayout" package="com.xingin.xhs" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[0,0][1080,2118]" drawing-order="1" hint="">
<node index="0" text="" resource-id="" class="android.widget.FrameLayout" package="com.xingin.xhs" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[0,0][1080,2118]" drawing-order="2" hint="">
<node index="0" text="" resource-id="com.xingin.xhs:id/0_resource_name_obfuscated" class="android.widget.LinearLayout" package="com.xingin.xhs" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[0,0][1080,2118]" drawing-order="1" hint="">
<node index="0" text="" resource-id="android:id/content" class="android.widget.FrameLayout" package="com.xingin.xhs" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[0,0][1080,2118]" drawing-order="2" hint="">
<node index="0" text="" resource-id="" class="android.widget.FrameLayout" package="com.xingin.xhs" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[0,0][1080,2118]" drawing-order="1" hint="">
<node NAF="true" index="0" text="" resource-id="com.xingin.xhs:id/0_resource_name_obfuscated" class="android.view.View" package="com.xingin.xhs" content-desc="" checkable="false" checked="false" clickable="true" enabled="true" focusable="true" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[0,0][1080,2118]" drawing-order="1" hint="" />
<node index="1" text="" resource-id="com.xingin.xhs:id/0_resource_name_obfuscated" class="android.view.ViewGroup" package="com.xingin.xhs" content-desc="" checkable="false" checked="false" clickable="true" enabled="true" focusable="true" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[0,947][1080,2118]" drawing-order="2" hint="">
<node index="0" text="" resource-id="com.xingin.xhs:id/0_resource_name_obfuscated" class="android.widget.FrameLayout" package="com.xingin.xhs" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[0,947][1080,1068]" drawing-order="1" hint="">
<node index="0" text="帮助" resource-id="com.xingin.xhs:id/0_resource_name_obfuscated" class="android.widget.TextView" package="com.xingin.xhs" content-desc="" checkable="false" checked="false" clickable="true" enabled="true" focusable="true" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[44,982][132,1032]" drawing-order="2" hint="" />
<node NAF="true" index="1" text="" resource-id="com.xingin.xhs:id/0_resource_name_obfuscated" class="android.widget.ImageView" package="com.xingin.xhs" content-desc="" checkable="false" checked="false" clickable="true" enabled="true" focusable="true" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[981,980][1036,1035]" drawing-order="1" hint="" />
</node>
<node index="1" text="" resource-id="com.xingin.xhs:id/0_resource_name_obfuscated" class="android.widget.LinearLayout" package="com.xingin.xhs" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[0,1090][1080,1156]" drawing-order="2" hint="">
<node index="0" text="登录后发现精彩内容" resource-id="com.xingin.xhs:id/0_resource_name_obfuscated" class="android.widget.TextView" package="com.xingin.xhs" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[342,1090][738,1156]" drawing-order="2" hint="" />
</node>
<node index="2" text="" resource-id="com.xingin.xhs:id/0_resource_name_obfuscated" class="android.widget.FrameLayout" package="com.xingin.xhs" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[0,1156][1080,2118]" drawing-order="3" hint="">
<node index="0" text="" resource-id="com.xingin.xhs:id/0_resource_name_obfuscated" class="android.view.ViewGroup" package="com.xingin.xhs" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[0,1156][1080,1829]" drawing-order="1" hint="">
<node index="0" text="+86 153 **** 0635" resource-id="com.xingin.xhs:id/0_resource_name_obfuscated" class="android.widget.TextView" package="com.xingin.xhs" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[288,1200][793,1275]" drawing-order="6" hint="" />
<node index="1" text="" resource-id="com.xingin.xhs:id/0_resource_name_obfuscated" class="android.widget.LinearLayout" package="com.xingin.xhs" content-desc="" checkable="false" checked="false" clickable="true" enabled="true" focusable="true" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[110,1407][970,1539]" drawing-order="5" hint="">
<node index="0" text="一键登录" resource-id="com.xingin.xhs:id/0_resource_name_obfuscated" class="android.widget.TextView" package="com.xingin.xhs" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[452,1447][628,1498]" drawing-order="2" hint="" />
</node>
<node index="2" text="其他登录方式" resource-id="com.xingin.xhs:id/0_resource_name_obfuscated" class="android.widget.TextView" package="com.xingin.xhs" content-desc="" checkable="false" checked="false" clickable="true" enabled="true" focusable="true" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[422,1621][658,1659]" drawing-order="3" hint="" />
<node index="3" text="" resource-id="com.xingin.xhs:id/0_resource_name_obfuscated" class="android.widget.LinearLayout" package="com.xingin.xhs" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[85,1747][995,1829]" drawing-order="1" hint="">
<node NAF="true" index="0" text="" resource-id="com.xingin.xhs:id/0_resource_name_obfuscated" class="android.widget.ImageView" package="com.xingin.xhs" content-desc="" checkable="false" checked="false" clickable="true" enabled="true" focusable="true" focused="false" scrollable="false" long-clickable="false" password="false" selected="true" visible-to-user="true" bounds="[110,1747][143,1780]" drawing-order="1" hint="" />
<node index="1" text="我已阅读并同意《用户协议》《隐私政策》《未成年人个人信息保护规则》" resource-id="com.xingin.xhs:id/0_resource_name_obfuscated" class="android.widget.TextView" package="com.xingin.xhs" content-desc="" checkable="false" checked="false" clickable="true" enabled="true" focusable="true" focused="false" scrollable="false" long-clickable="true" password="false" selected="false" visible-to-user="true" bounds="[154,1747][970,1827]" drawing-order="2" hint="" />
</node>
</node>
</node>
</node>
</node>
</node>
</node>
</node>
</node>
</node>
</node>
<node index="0" text="" resource-id="" class="android.widget.FrameLayout" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[0,0][1080,89]" drawing-order="0" hint="">
<node index="1" text="" resource-id="com.android.systemui:id/scrim_behind" class="android.view.View" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[0,0][1080,89]" drawing-order="2" hint="" />
<node index="2" text="" resource-id="com.android.systemui:id/scrim_in_front" class="android.view.View" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[0,0][1080,89]" drawing-order="9" hint="" />
<node index="3" text="" resource-id="" class="android.view.View" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[0,0][1080,89]" drawing-order="11" hint="" />
<node index="4" text="" resource-id="com.android.systemui:id/status_bar_container" class="android.widget.FrameLayout" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[0,0][1080,89]" drawing-order="4" hint="">
<node index="0" text="" resource-id="com.android.systemui:id/status_bar" class="android.widget.FrameLayout" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[0,0][1080,89]" drawing-order="1" hint="">
<node index="0" text="" resource-id="com.android.systemui:id/phone_status_bar_contents_container" class="android.widget.LinearLayout" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[19,0][1061,89]" drawing-order="3" hint="">
<node index="0" text="" resource-id="com.android.systemui:id/clock_container" class="android.widget.FrameLayout" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[27,6][231,89]" drawing-order="1" hint="">
<node index="0" text="" resource-id="com.android.systemui:id/leftside" class="android.widget.LinearLayout" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[27,6][231,89]" drawing-order="1" hint="">
<node index="0" text="9:56" resource-id="com.android.systemui:id/clock" class="android.widget.TextView" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[27,6][118,89]" drawing-order="10" hint="" />
<node index="2" text="" resource-id="com.android.systemui:id/notification_icon_area" class="android.widget.FrameLayout" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[118,6][231,89]" drawing-order="12" hint="">
<node index="0" text="" resource-id="com.android.systemui:id/notification_icon_area_inner" class="android.widget.LinearLayout" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[118,6][231,89]" drawing-order="1" hint="">
<node index="0" text="" resource-id="com.android.systemui:id/notificationIcons" class="android.widget.FrameLayout" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[118,6][231,89]" drawing-order="1" hint="">
<node index="0" text="" resource-id="" class="android.widget.ImageView" package="com.android.systemui" content-desc="Android 系统通知:已安装证书授权中心" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[218,29][231,65]" drawing-order="32" hint="" />
<node index="1" text="" resource-id="" class="android.widget.ImageView" package="com.android.systemui" content-desc="MIUI SDK通知:系统恢复" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[218,29][231,65]" drawing-order="31" hint="" />
<node index="2" text="" resource-id="" class="android.widget.ImageView" package="com.android.systemui" content-desc="内容中心通知:女子和大爷发生关系 事后称还没离婚" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[218,29][231,65]" drawing-order="30" hint="" />
<node index="3" text="" resource-id="" class="android.widget.ImageView" package="com.android.systemui" content-desc="内容中心通知:14岁男孩遭性侵80次 痛苦将伴随到死" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[218,29][231,65]" drawing-order="29" hint="" />
<node index="4" text="" resource-id="" class="android.widget.ImageView" package="com.android.systemui" content-desc="内容中心通知:男子与2人进行高风险性行为 确诊猴痘" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[218,29][231,65]" drawing-order="28" hint="" />
<node index="5" text="" resource-id="" class="android.widget.ImageView" package="com.android.systemui" content-desc="浏览器通知:存款20万以上的家庭,注意!" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[218,29][231,65]" drawing-order="27" hint="" />
<node index="6" text="" resource-id="" class="android.widget.ImageView" package="com.android.systemui" content-desc="内容中心通知:2女子酒店开房 一丝不挂被陌生人看光" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[218,29][231,65]" drawing-order="26" hint="" />
<node index="7" text="" resource-id="" class="android.widget.ImageView" package="com.android.systemui" content-desc="浏览器通知:00后情侣住酒店145天把客房变垃圾场" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[218,29][231,65]" drawing-order="25" hint="" />
<node index="8" text="" resource-id="" class="android.widget.ImageView" package="com.android.systemui" content-desc="浏览器通知:2女子酒店开房 一丝不挂被陌生人看光" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[218,29][231,65]" drawing-order="24" hint="" />
<node index="9" text="" resource-id="" class="android.widget.ImageView" package="com.android.systemui" content-desc="内容中心通知:女子与男网友发生关系 事后双双报警" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[218,29][231,65]" drawing-order="23" hint="" />
<node index="10" text="" resource-id="" class="android.widget.ImageView" package="com.android.systemui" content-desc="浏览器通知:存款超30万的家庭有多少?" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[218,29][231,65]" drawing-order="22" hint="" />
<node index="11" text="" resource-id="" class="android.widget.ImageView" package="com.android.systemui" content-desc="应用商店通知:内存还有提升空间" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[218,29][231,65]" drawing-order="21" hint="" />
<node index="12" text="" resource-id="" class="android.widget.ImageView" package="com.android.systemui" content-desc="浏览器通知:92号汽油或迎大幅跌价" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[218,29][231,65]" drawing-order="20" hint="" />
<node index="13" text="" resource-id="" class="android.widget.ImageView" package="com.android.systemui" content-desc="内容中心通知:16岁少女被2名男子强奸后丢弃路边" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[218,29][231,65]" drawing-order="19" hint="" />
<node index="14" text="" resource-id="" class="android.widget.ImageView" package="com.android.systemui" content-desc="浏览器通知:女子与男网友发生关系 事后双双报警" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[218,29][231,65]" drawing-order="16" hint="" />
<node index="15" text="" resource-id="" class="android.widget.ImageView" package="com.android.systemui" content-desc="浏览器通知:情侣住酒店145天 工作人员开门后傻眼" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[218,29][231,65]" drawing-order="18" hint="" />
<node index="16" text="" resource-id="" class="android.widget.ImageView" package="com.android.systemui" content-desc="内容中心通知:男子与少女发生关系时被撞破 17人被抓" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[218,29][231,65]" drawing-order="17" hint="" />
<node index="17" text="" resource-id="" class="android.widget.ImageView" package="com.android.systemui" content-desc="智能服务通知:上大众点评,领63元券包,美食吃到爽" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[168,29][218,65]" drawing-order="2" hint="" />
<node index="18" text="" resource-id="" class="android.widget.ImageView" package="com.android.systemui" content-desc="智能服务通知:脾气暴火气大的人,更伤血管?" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[118,29][168,65]" drawing-order="1" hint="" />
<node index="19" text="" resource-id="" class="android.widget.ImageView" package="com.android.systemui" content-desc="通话管理通知:02382051461" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[218,29][231,65]" drawing-order="15" hint="" />
<node index="20" text="" resource-id="" class="android.widget.ImageView" package="com.android.systemui" content-desc="智能服务通知:美团发外卖红包了" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[218,29][231,65]" drawing-order="13" hint="" />
<node index="21" text="" resource-id="" class="android.widget.ImageView" package="com.android.systemui" content-desc="浏览器通知:16岁少女被2名男子强奸后丢弃路边" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[218,29][231,65]" drawing-order="14" hint="" />
<node index="22" text="" resource-id="" class="android.widget.ImageView" package="com.android.systemui" content-desc="内容中心通知:34岁女教师性侵14岁男生 还发照引诱" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[218,29][231,65]" drawing-order="12" hint="" />
<node index="23" text="" resource-id="" class="android.widget.ImageView" package="com.android.systemui" content-desc="智能服务通知:美食团购券现在可领!" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[218,29][231,65]" drawing-order="11" hint="" />
<node index="24" text="" resource-id="" class="android.widget.ImageView" package="com.android.systemui" content-desc="智能服务通知:从“看中国”到“体验中国” 外国游客爱上沉浸式中国游" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[218,29][231,65]" drawing-order="4" hint="" />
<node index="25" text="" resource-id="" class="android.widget.ImageView" package="com.android.systemui" content-desc="智能服务通知:一键开启,帮你发现购物优惠" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[218,29][231,65]" drawing-order="3" hint="" />
<node index="26" text="" resource-id="" class="android.widget.ImageView" package="com.android.systemui" content-desc="智能服务通知:小众风味夜宵特惠" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[218,29][231,65]" drawing-order="8" hint="" />
<node index="27" text="" resource-id="" class="android.widget.ImageView" package="com.android.systemui" content-desc="应用商店通知:82%的用户已更新这58款应用" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[218,29][231,65]" drawing-order="10" hint="" />
<node index="28" text="" resource-id="" class="android.widget.ImageView" package="com.android.systemui" content-desc="内容中心通知:社保缴费基数变了 8省份进入“1时代”" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[218,29][231,65]" drawing-order="9" hint="" />
<node index="29" text="" resource-id="" class="android.widget.ImageView" package="com.android.systemui" content-desc="浏览器通知:养老金补发,工龄35年能补发900元?" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[218,29][231,65]" drawing-order="7" hint="" />
<node index="30" text="" resource-id="" class="android.widget.ImageView" package="com.android.systemui" content-desc="浏览器通知:34岁女教师性侵14岁男生 还发照引诱" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[218,29][231,65]" drawing-order="6" hint="" />
<node index="31" text="" resource-id="" class="android.widget.ImageView" package="com.android.systemui" content-desc="应用商店通知:小红书有新版本啦~" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[218,29][231,65]" drawing-order="5" hint="" />
</node>
</node>
</node>
</node>
</node>
<node index="1" text="" resource-id="" class="android.widget.FrameLayout" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[231,6][853,89]" drawing-order="2" hint="" />
<node index="2" text="" resource-id="com.android.systemui:id/system_icon_area" class="android.widget.LinearLayout" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[853,6][1049,89]" drawing-order="3" hint="">
<node index="0" text="" resource-id="com.android.systemui:id/system_icons" class="android.widget.LinearLayout" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="true" focused="true" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[853,17][1049,77]" drawing-order="1" hint="">
<node index="0" text="" resource-id="com.android.systemui:id/signal_cluster_view" class="android.widget.LinearLayout" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[853,19][965,75]" drawing-order="5" hint="">
<node index="0" text="" resource-id="com.android.systemui:id/signal_cluster" class="android.widget.LinearLayout" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="true" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[853,19][965,75]" drawing-order="1" hint="">
<node index="0" text="" resource-id="com.android.systemui:id/mobile_signal_group_0" class="android.widget.LinearLayout" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="true" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[853,19][907,75]" drawing-order="4" hint="">
<node index="0" text="" resource-id="com.android.systemui:id/mobile_combo" class="android.widget.LinearLayout" package="com.android.systemui" content-desc="4G 手机信号满格。" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[853,19][907,75]" drawing-order="1" hint="">
<node index="0" text="" resource-id="" class="android.widget.FrameLayout" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[853,19][907,75]" drawing-order="6" hint="">
<node index="0" text="" resource-id="" class="android.widget.FrameLayout" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[853,19][907,75]" drawing-order="1" hint="">
<node index="0" text="" resource-id="com.android.systemui:id/notch_volte" class="android.widget.ImageView" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[853,19][907,75]" drawing-order="1" hint="" />
<node index="1" text="" resource-id="com.android.systemui:id/mobile_signal" class="android.widget.ImageView" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[853,19][907,75]" drawing-order="4" hint="" />
</node>
</node>
</node>
</node>
<node index="1" text="" resource-id="com.android.systemui:id/wifi_combo" class="android.widget.FrameLayout" package="com.android.systemui" content-desc="WLAN 信号满格。" checkable="false" checked="false" clickable="false" enabled="true" focusable="true" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[907,19][965,75]" drawing-order="14" hint="">
<node index="0" text="" resource-id="com.android.systemui:id/wifi_signal" class="android.widget.ImageView" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[907,19][965,75]" drawing-order="1" hint="" />
<node index="1" text="" resource-id="com.android.systemui:id/wifi_inout" class="android.widget.ImageView" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[939,19][965,75]" drawing-order="3" hint="" />
</node>
</node>
</node>
<node index="1" text="" resource-id="com.android.systemui:id/battery" class="android.widget.LinearLayout" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="true" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[965,17][1049,77]" drawing-order="6" hint="">
<node index="0" text="" resource-id="" class="android.widget.FrameLayout" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[965,19][1049,75]" drawing-order="1" hint="">
<node index="0" text="" resource-id="com.android.systemui:id/battery_image" class="android.widget.ImageView" package="com.android.systemui" content-desc="正在充电,已完成百分之100。" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[965,19][1049,75]" drawing-order="1" hint="" />
<node index="1" text="100" resource-id="com.android.systemui:id/battery_digit" class="android.widget.TextView" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[985,19][1023,75]" drawing-order="3" hint="" />
</node>
</node>
</node>
</node>
</node>
</node>
</node>
</node>
</hierarchy>
\ No newline at end of file
<?xml version='1.0' encoding='UTF-8' standalone='yes' ?>
<hierarchy rotation="0">
<node index="0" text="" resource-id="" class="android.widget.LinearLayout" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[0,2118][1080,2248]" drawing-order="0" hint="">
<node index="0" text="" resource-id="com.android.systemui:id/rot0" class="android.widget.FrameLayout" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[0,2118][1080,2248]" drawing-order="1" hint="">
<node index="0" text="" resource-id="com.android.systemui:id/deadzone" class="android.view.View" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[0,2118][1080,2248]" drawing-order="3" hint="" />
<node index="1" text="" resource-id="com.android.systemui:id/nav_buttons" class="android.widget.LinearLayout" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[0,2118][1080,2248]" drawing-order="1" hint="">
<node index="0" text="" resource-id="com.android.systemui:id/start_padding" class="android.widget.FrameLayout" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[0,2118][233,2248]" drawing-order="1" hint="" />
<node index="1" text="" resource-id="com.android.systemui:id/recent_apps" class="android.widget.ImageView" package="com.android.systemui" content-desc="概览" checkable="false" checked="false" clickable="true" enabled="true" focusable="true" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[233,2118][398,2245]" drawing-order="2" hint="" />
<node index="2" text="" resource-id="com.android.systemui:id/home" class="android.widget.ImageView" package="com.android.systemui" content-desc="主屏幕" checkable="false" checked="false" clickable="true" enabled="true" focusable="true" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[457,2118][622,2245]" drawing-order="4" hint="" />
<node index="3" text="" resource-id="com.android.systemui:id/back" class="android.widget.ImageView" package="com.android.systemui" content-desc="返回" checkable="false" checked="false" clickable="true" enabled="true" focusable="true" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[681,2118][846,2245]" drawing-order="6" hint="" />
<node index="4" text="" resource-id="com.android.systemui:id/side_padding" class="android.widget.FrameLayout" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[846,2118][1080,2248]" drawing-order="7" hint="" />
</node>
</node>
</node>
<node index="0" text="" resource-id="" class="android.widget.FrameLayout" package="com.xingin.xhs" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[0,0][1080,2248]" drawing-order="0" hint="">
<node index="0" text="" resource-id="com.xingin.xhs:id/0_resource_name_obfuscated" class="android.widget.FrameLayout" package="com.xingin.xhs" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[0,0][1080,2248]" drawing-order="1" hint="">
<node index="0" text="" resource-id="" class="android.widget.LinearLayout" package="com.xingin.xhs" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[0,0][1080,2118]" drawing-order="1" hint="">
<node index="0" text="" resource-id="" class="android.widget.FrameLayout" package="com.xingin.xhs" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[0,0][1080,2118]" drawing-order="2" hint="">
<node index="0" text="" resource-id="com.xingin.xhs:id/0_resource_name_obfuscated" class="android.widget.LinearLayout" package="com.xingin.xhs" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[0,0][1080,2118]" drawing-order="1" hint="">
<node index="0" text="" resource-id="android:id/content" class="android.widget.FrameLayout" package="com.xingin.xhs" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[0,0][1080,2118]" drawing-order="2" hint="">
<node index="0" text="" resource-id="com.xingin.xhs:id/0_resource_name_obfuscated" class="android.widget.FrameLayout" package="com.xingin.xhs" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[0,0][1080,2118]" drawing-order="1" hint="">
<node index="0" text="" resource-id="com.xingin.xhs:id/0_resource_name_obfuscated" class="android.widget.FrameLayout" package="com.xingin.xhs" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[0,0][1080,2118]" drawing-order="1" hint="" />
<node index="1" text="" resource-id="com.xingin.xhs:id/0_resource_name_obfuscated" class="android.widget.FrameLayout" package="com.xingin.xhs" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[0,0][1080,2118]" drawing-order="2" hint="">
<node index="0" text="" resource-id="" class="android.widget.RelativeLayout" package="com.xingin.xhs" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[0,0][1080,2118]" drawing-order="1" hint="">
<node index="0" text="" resource-id="" class="android.view.ViewGroup" package="com.xingin.xhs" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[0,0][1080,2118]" drawing-order="1" hint="">
<node index="0" text="帮助" resource-id="com.xingin.xhs:id/0_resource_name_obfuscated" class="android.widget.TextView" package="com.xingin.xhs" content-desc="帮助" checkable="false" checked="false" clickable="true" enabled="true" focusable="true" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[948,154][1036,204]" drawing-order="2" hint="" />
<node index="1" text="" resource-id="com.xingin.xhs:id/0_resource_name_obfuscated" class="android.widget.ImageView" package="com.xingin.xhs" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[335,583][745,800]" drawing-order="3" hint="" />
<node index="2" text="" resource-id="com.xingin.xhs:id/0_resource_name_obfuscated" class="android.widget.LinearLayout" package="com.xingin.xhs" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[160,1382][916,1694]" drawing-order="4" hint="">
<node index="0" text="" resource-id="" class="android.widget.LinearLayout" package="com.xingin.xhs" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[160,1382][916,1547]" drawing-order="1" hint="">
<node index="0" text="" resource-id="com.xingin.xhs:id/0_resource_name_obfuscated" class="android.view.ViewGroup" package="com.xingin.xhs" content-desc="" checkable="false" checked="false" clickable="true" enabled="true" focusable="true" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[160,1426][916,1547]" drawing-order="2" hint="">
<node index="0" text="手机号登录" resource-id="com.xingin.xhs:id/0_resource_name_obfuscated" class="android.widget.Button" package="com.xingin.xhs" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[410,1459][666,1514]" drawing-order="1" hint="" />
</node>
</node>
<node index="1" text="" resource-id="com.xingin.xhs:id/0_resource_name_obfuscated" class="android.widget.LinearLayout" package="com.xingin.xhs" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[160,1591][916,1694]" drawing-order="3" hint="">
<node index="0" text="" resource-id="com.xingin.xhs:id/0_resource_name_obfuscated" class="android.widget.Button" package="com.xingin.xhs" content-desc="未选中,同意" checkable="false" checked="false" clickable="true" enabled="true" focusable="true" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[160,1597][199,1636]" drawing-order="1" hint="" />
<node index="1" text="我已阅读并同意《用户协议》《隐私政策》《未成年人个人信息保护规则》" resource-id="com.xingin.xhs:id/0_resource_name_obfuscated" class="android.widget.TextView" package="com.xingin.xhs" content-desc="我已阅读并同意《用户协议》《隐私政策》《未成年人个人信息保护规则》" checkable="false" checked="false" clickable="true" enabled="true" focusable="true" focused="false" scrollable="false" long-clickable="true" password="false" selected="false" visible-to-user="true" bounds="[210,1591][916,1694]" drawing-order="2" hint="" />
</node>
</node>
<node index="3" text="" resource-id="com.xingin.xhs:id/0_resource_name_obfuscated" class="android.widget.LinearLayout" package="com.xingin.xhs" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[375,1931][705,1969]" drawing-order="5" hint="">
<node index="0" text="账号丢失了?" resource-id="com.xingin.xhs:id/0_resource_name_obfuscated" class="android.widget.TextView" package="com.xingin.xhs" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[375,1931][573,1969]" drawing-order="1" hint="" />
<node index="1" text="找回账号" resource-id="com.xingin.xhs:id/0_resource_name_obfuscated" class="android.widget.Button" package="com.xingin.xhs" content-desc="找回账号" checkable="false" checked="false" clickable="true" enabled="true" focusable="true" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[573,1931][705,1969]" drawing-order="2" hint="" />
</node>
</node>
</node>
</node>
</node>
</node>
</node>
</node>
</node>
</node>
</node>
<node index="0" text="" resource-id="" class="android.widget.FrameLayout" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[0,0][1080,89]" drawing-order="0" hint="">
<node index="1" text="" resource-id="com.android.systemui:id/scrim_in_front" class="android.view.View" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[0,0][1080,89]" drawing-order="8" hint="" />
<node index="2" text="" resource-id="com.android.systemui:id/scrim_behind" class="android.view.View" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[0,0][1080,89]" drawing-order="2" hint="" />
<node index="3" text="" resource-id="" class="android.view.View" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[0,0][1080,89]" drawing-order="9" hint="" />
<node index="4" text="" resource-id="com.android.systemui:id/status_bar_container" class="android.widget.FrameLayout" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[0,0][1080,89]" drawing-order="4" hint="">
<node index="0" text="" resource-id="com.android.systemui:id/status_bar" class="android.widget.FrameLayout" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[0,0][1080,86]" drawing-order="1" hint="">
<node index="0" text="" resource-id="com.android.systemui:id/phone_status_bar_contents_container" class="android.widget.LinearLayout" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[19,0][1061,86]" drawing-order="3" hint="">
<node index="0" text="" resource-id="com.android.systemui:id/clock_container" class="android.widget.FrameLayout" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[27,3][231,86]" drawing-order="1" hint="">
<node index="0" text="" resource-id="com.android.systemui:id/leftside" class="android.widget.LinearLayout" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[27,3][231,86]" drawing-order="1" hint="">
<node index="0" text="上午7:57" resource-id="com.android.systemui:id/clock" class="android.widget.TextView" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[52,3][205,86]" drawing-order="1" hint="" />
</node>
</node>
<node index="1" text="" resource-id="" class="android.widget.FrameLayout" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[231,3][847,86]" drawing-order="2" hint="" />
<node index="2" text="" resource-id="com.android.systemui:id/system_icon_area" class="android.widget.LinearLayout" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[847,3][1049,86]" drawing-order="3" hint="">
<node index="0" text="" resource-id="com.android.systemui:id/system_icons" class="android.widget.LinearLayout" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="true" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[847,14][1049,74]" drawing-order="1" hint="">
<node index="0" text="" resource-id="com.android.systemui:id/signal_cluster_view" class="android.widget.LinearLayout" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[847,14][965,74]" drawing-order="5" hint="">
<node index="0" text="" resource-id="com.android.systemui:id/signal_cluster" class="android.widget.LinearLayout" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="true" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[847,14][965,74]" drawing-order="1" hint="">
<node index="0" text="" resource-id="com.android.systemui:id/mobile_signal_group_dual_notch" class="android.widget.LinearLayout" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="true" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[847,14][857,74]" drawing-order="9" hint="">
<node index="0" text="" resource-id="com.android.systemui:id/mobile_combo" class="android.widget.LinearLayout" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[847,14][857,74]" drawing-order="1" hint="">
<node index="1" text="" resource-id="com.android.systemui:id/carrier" class="android.widget.TextView" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[847,14][852,74]" drawing-order="2" hint="" />
<node index="2" text="" resource-id="com.android.systemui:id/mobile_type" class="android.widget.TextView" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[852,14][857,74]" drawing-order="3" hint="" />
</node>
</node>
<node index="3" text="" resource-id="com.android.systemui:id/no_sims_combo" class="android.widget.FrameLayout" package="com.android.systemui" content-desc="没有 SIM 卡。" checkable="false" checked="false" clickable="false" enabled="true" focusable="true" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[857,16][907,72]" drawing-order="10" hint="">
<node index="1" text="" resource-id="com.android.systemui:id/no_sims_dark" class="android.widget.ImageView" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[857,16][907,72]" drawing-order="2" hint="" />
</node>
<node index="4" text="" resource-id="com.android.systemui:id/wifi_combo" class="android.widget.FrameLayout" package="com.android.systemui" content-desc="WLAN 信号满格。" checkable="false" checked="false" clickable="false" enabled="true" focusable="true" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[907,16][965,72]" drawing-order="13" hint="">
<node index="0" text="" resource-id="com.android.systemui:id/wifi_signal" class="android.widget.ImageView" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[907,16][965,72]" drawing-order="1" hint="" />
<node index="1" text="" resource-id="com.android.systemui:id/wifi_inout" class="android.widget.ImageView" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[907,16][965,72]" drawing-order="3" hint="" />
</node>
</node>
</node>
<node index="1" text="" resource-id="com.android.systemui:id/battery" class="android.widget.LinearLayout" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="true" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[965,14][1049,74]" drawing-order="6" hint="">
<node index="0" text="" resource-id="" class="android.widget.FrameLayout" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[965,16][1049,72]" drawing-order="1" hint="">
<node index="0" text="" resource-id="com.android.systemui:id/battery_image" class="android.widget.ImageView" package="com.android.systemui" content-desc="正在充电,已完成百分之100。" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[965,16][1049,72]" drawing-order="1" hint="" />
<node index="1" text="100" resource-id="com.android.systemui:id/battery_digit" class="android.widget.TextView" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[989,16][1025,72]" drawing-order="3" hint="" />
</node>
</node>
</node>
</node>
</node>
<node index="1" text="" resource-id="" class="android.widget.FrameLayout" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[19,38][231,44]" drawing-order="4" hint="">
<node index="0" text="" resource-id="com.android.systemui:id/notchLeftEar" class="android.widget.FrameLayout" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[27,38][231,44]" drawing-order="1" hint="" />
</node>
</node>
</node>
</node>
</hierarchy>
\ No newline at end of file
This source diff could not be displayed because it is too large. You can view the blob instead.
2026-08-14 09:48:11.138 | INFO | __main__:main:950 - 本程序使用现有 ADB Server 127.0.0.1:5037,所有恢复命令都限定到当前手机,不操作其他手机连接
2026-08-14 09:48:11.147 | SUCCESS | __main__:main:969 - 172.20.1.44 子进程启动成功,pid=20332
2026-08-14 09:48:11.154 | SUCCESS | __main__:main:969 - 172.20.1.25 子进程启动成功,pid=11748
2026-08-14 09:48:15.891 | SUCCESS | __mp_main__:wait_until_online:732 - 172.20.1.44:5555 ADB 已连续稳定 5 秒(端口 5037)
2026-08-14 09:48:15.903 | SUCCESS | __mp_main__:wait_until_online:732 - 172.20.1.25:5555 ADB 已连续稳定 5 秒(端口 5037)
2026-08-14 09:48:23.247 | SUCCESS | __mp_main__:check_status:562 - com.xingin.alioth.search.GlobalSearchActivity
2026-08-14 09:48:23.335 | SUCCESS | __mp_main__:worker:918 - 172.20.1.25 当前搜索用户:6846395e000000001d026d76 42275720349
2026-08-14 09:48:24.326 | SUCCESS | __mp_main__:check_status:562 - com.xingin.matrix.v2.profile.newpage.NewOtherUserActivity
2026-08-14 09:48:24.326 | SUCCESS | __mp_main__:check_status:574 - 正在用户详情页面 回退
2026-08-14 09:48:25.152 | SUCCESS | __mp_main__:check_status:562 - com.xingin.alioth.search.GlobalSearchActivity
2026-08-14 09:48:25.152 | SUCCESS | __mp_main__:_search_user_id_first:499 - 先使用 user_id 搜索达人: 6846395e000000001d026d76
2026-08-14 09:48:25.696 | SUCCESS | __mp_main__:_open_search_input:385 - 清空上次搜索内容
2026-08-14 09:48:28.745 | SUCCESS | __mp_main__:check_status:562 - com.xingin.alioth.search.GlobalSearchActivity
2026-08-14 09:48:28.852 | SUCCESS | __mp_main__:worker:918 - 172.20.1.44 当前搜索用户:59c12e4150c4b45e2db6fff1 956626687
2026-08-14 09:48:29.740 | SUCCESS | __mp_main__:check_status:562 - com.xingin.alioth.search.GlobalSearchActivity
2026-08-14 09:48:29.741 | SUCCESS | __mp_main__:_search_user_id_first:499 - 先使用 user_id 搜索达人: 59c12e4150c4b45e2db6fff1
2026-08-14 09:48:30.515 | SUCCESS | __mp_main__:_open_search_input:385 - 清空上次搜索内容
2026-08-14 09:48:33.089 | ERROR | __mp_main__:_search_user_id_first:515 - user_id 搜索未找到用户结果: 6846395e000000001d026d76
2026-08-14 09:48:33.591 | SUCCESS | __mp_main__:_open_search_input:385 - 清空上次搜索内容
2026-08-14 09:48:42.060 | SUCCESS | __mp_main__:_search_user_id_first:510 - user_id 搜索命中用户列表第一条,进入达人主页: 59c12e4150c4b45e2db6fff1
2026-08-14 09:48:42.465 | SUCCESS | __mp_main__:human_like_scroll:253 - xhs_app:172.20.1.44 user_id -> 59c12e4150c4b45e2db6fff1 spider_count -> 1
2026-08-14 09:48:43.811 | ERROR | __mp_main__:do_search_scroll:532 - 没有找到用户 尝试点击用户界面 进行查找
2026-08-14 09:48:43.889 | SUCCESS | __mp_main__:human_like_scroll:253 - xhs_app:172.20.1.44 user_id -> 59c12e4150c4b45e2db6fff1 spider_count -> 1
2026-08-14 09:48:43.945 | SUCCESS | __mp_main__:do_search_scroll:537 - 不在用户页面 点击跳转到用户
2026-08-14 09:48:45.352 | SUCCESS | __mp_main__:human_like_scroll:253 - xhs_app:172.20.1.44 user_id -> 59c12e4150c4b45e2db6fff1 spider_count -> 1
2026-08-14 09:48:47.432 | SUCCESS | __mp_main__:human_like_scroll:253 - xhs_app:172.20.1.44 user_id -> 59c12e4150c4b45e2db6fff1 spider_count -> 1
2026-08-14 09:48:49.099 | SUCCESS | __mp_main__:human_like_scroll:253 - xhs_app:172.20.1.44 user_id -> 59c12e4150c4b45e2db6fff1 spider_count -> 1
2026-08-14 09:48:50.702 | SUCCESS | __mp_main__:human_like_scroll:253 - xhs_app:172.20.1.44 user_id -> 59c12e4150c4b45e2db6fff1 spider_count -> 1
2026-08-14 09:48:53.753 | SUCCESS | __mp_main__:human_like_scroll:253 - xhs_app:172.20.1.44 user_id -> 59c12e4150c4b45e2db6fff1 spider_count -> 1
2026-08-14 09:48:55.219 | SUCCESS | __mp_main__:human_like_scroll:253 - xhs_app:172.20.1.44 user_id -> 59c12e4150c4b45e2db6fff1 spider_count -> 1
2026-08-14 09:48:57.614 | SUCCESS | __mp_main__:human_like_scroll:253 - xhs_app:172.20.1.44 user_id -> 59c12e4150c4b45e2db6fff1 spider_count -> 2
2026-08-14 09:48:59.327 | SUCCESS | __mp_main__:human_like_scroll:253 - xhs_app:172.20.1.44 user_id -> 59c12e4150c4b45e2db6fff1 spider_count -> 2
2026-08-14 09:49:04.048 | ERROR | __mp_main__:worker:937 - 172.20.1.25 ADB 仍在线,保留当前任务并仅恢复 uiautomator 服务
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\multiprocessing\spawn.py", line 122, in spawn_main
exitcode = _main(fd, parent_sentinel)
│ │ └ 340
│ └ 3
└ <function _main at 0x0000017563AE1080>
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\multiprocessing\spawn.py", line 135, in _main
return self._bootstrap(parent_sentinel)
│ │ └ 340
│ └ <function BaseProcess._bootstrap at 0x00000175637E6E80>
└ <Process name='Process-2' parent=16452 started>
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\multiprocessing\process.py", line 313, in _bootstrap
self.run()
│ └ <function BaseProcess.run at 0x0000017563794CC0>
└ <Process name='Process-2' parent=16452 started>
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\multiprocessing\process.py", line 108, in run
self._target(*self._args, **self._kwargs)
│ │ │ │ │ └ {}
│ │ │ │ └ <Process name='Process-2' parent=16452 started>
│ │ │ └ ('172.20.1.25', 1)
│ │ └ <Process name='Process-2' parent=16452 started>
│ └ <function worker at 0x00000175671FD080>
└ <Process name='Process-2' parent=16452 started>
> File "C:\Users\cuish\auto_xhs\xhs_auto_app_search_user.py", line 919, in worker
auto_operation(d, user_id, red_id, client_ip)
│ │ │ │ └ '172.20.1.25'
│ │ │ └ '42275720349'
│ │ └ '6846395e000000001d026d76'
│ └ <uiautomator2.Device object at 0x000001756358E510>
└ <function auto_operation at 0x00000175671FCFE0>
File "C:\Users\cuish\auto_xhs\xhs_auto_app_search_user.py", line 877, in auto_operation
do_search_scroll(d, user_id, red_id, client_ip)
│ │ │ │ └ '172.20.1.25'
│ │ │ └ '42275720349'
│ │ └ '6846395e000000001d026d76'
│ └ <uiautomator2.Device object at 0x000001756358E510>
└ <function do_search_scroll at 0x00000175671FC4A0>
File "C:\Users\cuish\auto_xhs\xhs_auto_app_search_user.py", line 538, in do_search_scroll
d(text="用户").click()
└ <uiautomator2.Device object at 0x000001756358E510>
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\site-packages\uiautomator2\_selector.py", line 149, in click
self.must_wait(timeout=timeout)
│ │ └ None
│ └ <function UiObject.must_wait at 0x0000017566B159E0>
└ <uiautomator2._selector.UiObject object at 0x000001756719C7A0>
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\site-packages\uiautomator2\_selector.py", line 338, in must_wait
raise UiObjectNotFoundError({'code': -32002, 'data': str(self.selector), 'method': 'wait'})
│ │ └ {'mask': 1, 'childOrSibling': [], 'childOrSiblingSelector': [], 'text': '用户'}
│ └ <uiautomator2._selector.UiObject object at 0x000001756719C7A0>
└ <class 'uiautomator2.exceptions.UiObjectNotFoundError'>
uiautomator2.exceptions.UiObjectNotFoundError: {'code': -32002, 'data': "Selector [text='用户']", 'method': 'wait'}
2026-08-14 09:49:06.532 | SUCCESS | __mp_main__:human_like_scroll:253 - xhs_app:172.20.1.44 user_id -> 59c12e4150c4b45e2db6fff1 spider_count -> 2
2026-08-14 09:49:08.082 | SUCCESS | __mp_main__:human_like_scroll:253 - xhs_app:172.20.1.44 user_id -> 59c12e4150c4b45e2db6fff1 spider_count -> 2
2026-08-14 09:49:08.176 | SUCCESS | __mp_main__:wait_until_online:732 - 172.20.1.25:5555 ADB 已连续稳定 5 秒(端口 5037)
2026-08-14 09:49:09.906 | WARNING | __mp_main__:restart_service:768 - 172.20.1.25 执行 reset_uiautomator 失败: device offline
2026-08-14 09:49:09.906 | WARNING | __mp_main__:restart_service:789 - 172.20.1.25 无法确认服务已重启,后续继续尝试拉起 App: device offline
2026-08-14 09:49:14.727 | SUCCESS | __mp_main__:human_like_scroll:253 - xhs_app:172.20.1.44 user_id -> 59c12e4150c4b45e2db6fff1 spider_count -> 3
2026-08-14 09:49:14.907 | SUCCESS | __mp_main__:worker:918 - 172.20.1.25 当前搜索用户:6846395e000000001d026d76 42275720349
2026-08-14 09:49:15.917 | SUCCESS | __mp_main__:check_status:562 - com.xingin.alioth.search.GlobalSearchActivity
2026-08-14 09:49:15.917 | SUCCESS | __mp_main__:_search_user_id_first:499 - 先使用 user_id 搜索达人: 6846395e000000001d026d76
2026-08-14 09:49:16.493 | SUCCESS | __mp_main__:_open_search_input:385 - 清空上次搜索内容
2026-08-14 09:49:16.772 | SUCCESS | __mp_main__:human_like_scroll:253 - xhs_app:172.20.1.44 user_id -> 59c12e4150c4b45e2db6fff1 spider_count -> 3
2026-08-14 09:49:18.089 | SUCCESS | __mp_main__:human_like_scroll:253 - xhs_app:172.20.1.44 user_id -> 59c12e4150c4b45e2db6fff1 spider_count -> 3
2026-08-14 09:49:20.074 | SUCCESS | __mp_main__:human_like_scroll:253 - xhs_app:172.20.1.44 user_id -> 59c12e4150c4b45e2db6fff1 spider_count -> 3
2026-08-14 09:49:22.073 | SUCCESS | __mp_main__:human_like_scroll:253 - xhs_app:172.20.1.44 user_id -> 59c12e4150c4b45e2db6fff1 spider_count -> 3
2026-08-14 09:49:24.341 | SUCCESS | __mp_main__:human_like_scroll:253 - xhs_app:172.20.1.44 user_id -> 59c12e4150c4b45e2db6fff1 spider_count -> 4
2026-08-14 09:49:24.563 | ERROR | __mp_main__:_search_user_id_first:515 - user_id 搜索未找到用户结果: 6846395e000000001d026d76
2026-08-14 09:49:25.178 | SUCCESS | __mp_main__:_open_search_input:385 - 清空上次搜索内容
2026-08-14 09:49:25.983 | SUCCESS | __mp_main__:human_like_scroll:253 - xhs_app:172.20.1.44 user_id -> 59c12e4150c4b45e2db6fff1 spider_count -> 4
2026-08-14 09:49:28.436 | SUCCESS | __mp_main__:human_like_scroll:253 - xhs_app:172.20.1.44 user_id -> 59c12e4150c4b45e2db6fff1 spider_count -> 4
2026-08-14 09:49:28.574 | ERROR | __mp_main__:worker:931 - 172.20.1.25 ADB 状态异常(offline),准备重建当前手机会话
Traceback (most recent call last):
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\site-packages\uiautomator2\core.py", line 97, in connect
self.sock = self.__device.create_connection(adbutils.Network.TCP, self.__port)
│ │ │ │ │ │ └ <uiautomator2.core.AdbHTTPConnection object at 0x0000017567170C90>
│ │ │ │ │ └ <Network.TCP: 'tcp'>
│ │ │ │ └ <enum 'Network'>
│ │ │ └ <module 'adbutils' from 'C:\\Users\\cuish\\anaconda3\\envs\\xhs\\Lib\\site-packages\\adbutils\\__init__.py'>
│ │ └ <uiautomator2.core.AdbHTTPConnection object at 0x0000017567170C90>
│ └ None
└ <uiautomator2.core.AdbHTTPConnection object at 0x0000017567170C90>
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\site-packages\adbutils\_device_base.py", line 610, in create_connection
return _connect(c)
│ └ <adbutils._adb.AdbConnection object at 0x0000017567229730>
└ <function BaseDevice.create_connection.<locals>._connect at 0x00000175635AEDE0>
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\site-packages\adbutils\_device_base.py", line 591, in _connect
c.check_okay()
│ └ <function AdbConnection.check_okay at 0x0000017565D6A3E0>
└ <adbutils._adb.AdbConnection object at 0x0000017567229730>
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\site-packages\adbutils\_adb.py", line 192, in check_okay
raise AdbError(self.read_string_block())
│ │ └ <function AdbConnection.read_string_block at 0x0000017565D6A2A0>
│ └ <adbutils._adb.AdbConnection object at 0x0000017567229730>
└ <class 'adbutils.errors.AdbError'>
adbutils.errors.AdbError: closed
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\site-packages\uiautomator2\core.py", line 311, in jsonrpc_call
return _jsonrpc_call(self._dev, self._device_server_port, method, params, timeout, self._debug)
│ │ │ │ │ │ │ │ │ └ False
│ │ │ │ │ │ │ │ └ <uiautomator2.Device object at 0x000001756358E510>
│ │ │ │ │ │ │ └ 300
│ │ │ │ │ │ └ ({'mask': 64, 'childOrSibling': [], 'childOrSiblingSelector': [], 'description': '全部删除'},)
│ │ │ │ │ └ 'objInfo'
│ │ │ │ └ 9008
│ │ │ └ <uiautomator2.Device object at 0x000001756358E510>
│ │ └ AdbDevice(serial=172.20.1.25:5555)
│ └ <uiautomator2.Device object at 0x000001756358E510>
└ <function _jsonrpc_call at 0x0000017566B174C0>
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\site-packages\uiautomator2\core.py", line 173, in _jsonrpc_call
r = _http_request(dev, device_port, "POST", "/jsonrpc/0", payload, timeout=timeout, print_request=print_request)
│ │ │ │ │ └ False
│ │ │ │ └ 300
│ │ │ └ {'jsonrpc': '2.0', 'id': 1, 'method': 'objInfo', 'params': ({'mask': 64, 'childOrSibling': [], 'childOrSiblingSelector': [], ...
│ │ └ 9008
│ └ AdbDevice(serial=172.20.1.25:5555)
└ <function _http_request at 0x0000017566B17380>
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\site-packages\uiautomator2\core.py", line 139, in _http_request
conn.request(method, path, json.dumps(data), headers=headers)
│ │ │ │ │ │ │ └ {'User-Agent': 'uiautomator2', 'Accept-Encoding': '', 'Content-Type': 'application/json'}
│ │ │ │ │ │ └ {'jsonrpc': '2.0', 'id': 1, 'method': 'objInfo', 'params': ({'mask': 64, 'childOrSibling': [], 'childOrSiblingSelector': [], ...
│ │ │ │ │ └ <function dumps at 0x0000017565C50C20>
│ │ │ │ └ <module 'json' from 'C:\\Users\\cuish\\anaconda3\\envs\\xhs\\Lib\\json\\__init__.py'>
│ │ │ └ '/jsonrpc/0'
│ │ └ 'POST'
│ └ <function HTTPConnection.request at 0x0000017565E3E5C0>
└ <uiautomator2.core.AdbHTTPConnection object at 0x0000017567170C90>
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\http\client.py", line 1358, in request
self._send_request(method, url, body, headers, encode_chunked)
│ │ │ │ │ │ └ False
│ │ │ │ │ └ {'User-Agent': 'uiautomator2', 'Accept-Encoding': '', 'Content-Type': 'application/json'}
│ │ │ │ └ '{"jsonrpc": "2.0", "id": 1, "method": "objInfo", "params": [{"mask": 64, "childOrSibling": [], "childOrSiblingSelector": [],...
│ │ │ └ '/jsonrpc/0'
│ │ └ 'POST'
│ └ <function HTTPConnection._send_request at 0x0000017565E3E660>
└ <uiautomator2.core.AdbHTTPConnection object at 0x0000017567170C90>
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\http\client.py", line 1404, in _send_request
self.endheaders(body, encode_chunked=encode_chunked)
│ │ │ └ False
│ │ └ b'{"jsonrpc": "2.0", "id": 1, "method": "objInfo", "params": [{"mask": 64, "childOrSibling": [], "childOrSiblingSelector": []...
│ └ <function HTTPConnection.endheaders at 0x0000017565E3E520>
└ <uiautomator2.core.AdbHTTPConnection object at 0x0000017567170C90>
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\http\client.py", line 1353, in endheaders
self._send_output(message_body, encode_chunked=encode_chunked)
│ │ │ └ False
│ │ └ b'{"jsonrpc": "2.0", "id": 1, "method": "objInfo", "params": [{"mask": 64, "childOrSibling": [], "childOrSiblingSelector": []...
│ └ <function HTTPConnection._send_output at 0x0000017565E3E0C0>
└ <uiautomator2.core.AdbHTTPConnection object at 0x0000017567170C90>
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\http\client.py", line 1113, in _send_output
self.send(msg)
│ │ └ b'POST /jsonrpc/0 HTTP/1.1\r\nHost: localhost:9008\r\nContent-Length: 169\r\nUser-Agent: uiautomator2\r\nAccept-Encoding: \r\...
│ └ <function HTTPConnection.send at 0x0000017565E3DEE0>
└ <uiautomator2.core.AdbHTTPConnection object at 0x0000017567170C90>
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\http\client.py", line 1057, in send
self.connect()
│ └ <function AdbHTTPConnection.connect at 0x0000017566B171A0>
└ <uiautomator2.core.AdbHTTPConnection object at 0x0000017567170C90>
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\site-packages\uiautomator2\core.py", line 99, in connect
raise HTTPError(f"Unable to connect to uiautomator2 server: {e}") from e
└ <class 'uiautomator2.exceptions.HTTPError'>
uiautomator2.exceptions.HTTPError: Unable to connect to uiautomator2 server: closed
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\multiprocessing\spawn.py", line 122, in spawn_main
exitcode = _main(fd, parent_sentinel)
│ │ └ 340
│ └ 3
└ <function _main at 0x0000017563AE1080>
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\multiprocessing\spawn.py", line 135, in _main
return self._bootstrap(parent_sentinel)
│ │ └ 340
│ └ <function BaseProcess._bootstrap at 0x00000175637E6E80>
└ <Process name='Process-2' parent=16452 started>
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\multiprocessing\process.py", line 313, in _bootstrap
self.run()
│ └ <function BaseProcess.run at 0x0000017563794CC0>
└ <Process name='Process-2' parent=16452 started>
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\multiprocessing\process.py", line 108, in run
self._target(*self._args, **self._kwargs)
│ │ │ │ │ └ {}
│ │ │ │ └ <Process name='Process-2' parent=16452 started>
│ │ │ └ ('172.20.1.25', 1)
│ │ └ <Process name='Process-2' parent=16452 started>
│ └ <function worker at 0x00000175671FD080>
└ <Process name='Process-2' parent=16452 started>
> File "C:\Users\cuish\auto_xhs\xhs_auto_app_search_user.py", line 919, in worker
auto_operation(d, user_id, red_id, client_ip)
│ │ │ │ └ '172.20.1.25'
│ │ │ └ '42275720349'
│ │ └ '6846395e000000001d026d76'
│ └ <uiautomator2.Device object at 0x000001756358E510>
└ <function auto_operation at 0x00000175671FCFE0>
File "C:\Users\cuish\auto_xhs\xhs_auto_app_search_user.py", line 877, in auto_operation
do_search_scroll(d, user_id, red_id, client_ip)
│ │ │ │ └ '172.20.1.25'
│ │ │ └ '42275720349'
│ │ └ '6846395e000000001d026d76'
│ └ <uiautomator2.Device object at 0x000001756358E510>
└ <function do_search_scroll at 0x00000175671FC4A0>
File "C:\Users\cuish\auto_xhs\xhs_auto_app_search_user.py", line 523, in do_search_scroll
if _input_and_submit_search(d, red_id, current_keyword=user_id):
│ │ │ └ '6846395e000000001d026d76'
│ │ └ '42275720349'
│ └ <uiautomator2.Device object at 0x000001756358E510>
└ <function _input_and_submit_search at 0x00000175671FC180>
File "C:\Users\cuish\auto_xhs\xhs_auto_app_search_user.py", line 408, in _input_and_submit_search
if not _open_search_input(d, current_keyword):
│ │ └ '6846395e000000001d026d76'
│ └ <uiautomator2.Device object at 0x000001756358E510>
└ <function _open_search_input at 0x00000175671FC0E0>
File "C:\Users\cuish\auto_xhs\xhs_auto_app_search_user.py", line 392, in _open_search_input
d(description="全部删除").click()
└ <uiautomator2.Device object at 0x000001756358E510>
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\site-packages\uiautomator2\_selector.py", line 150, in click
x, y = self.center(offset=offset)
│ │ └ None
│ └ <function UiObject.center at 0x0000017566B15300>
└ <uiautomator2._selector.UiObject object at 0x000001756722A7B0>
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\site-packages\uiautomator2\_selector.py", line 171, in center
lx, ly, rx, ry = self.bounds()
│ └ <function UiObject.bounds at 0x0000017566B15260>
└ <uiautomator2._selector.UiObject object at 0x000001756722A7B0>
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\site-packages\uiautomator2\_selector.py", line 158, in bounds
info = self.info
│ └ <property object at 0x0000017566AD1580>
└ <uiautomator2._selector.UiObject object at 0x000001756722A7B0>
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\site-packages\uiautomator2\_selector.py", line 128, in info
return self.jsonrpc.objInfo(self.selector)
│ │ │ └ {'mask': 64, 'childOrSibling': [], 'childOrSiblingSelector': [], 'description': '全部删除'}
│ │ └ <uiautomator2._selector.UiObject object at 0x000001756722A7B0>
│ └ <uiautomator2.base._BaseClient.jsonrpc.<locals>.JSONRpcWrapper object at 0x000001756719AA50>
└ <uiautomator2._selector.UiObject object at 0x000001756722A7B0>
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\site-packages\uiautomator2\base.py", line 158, in __call__
return self.server.jsonrpc_call(self.method, params, http_timeout)
│ │ │ │ │ │ └ 300
│ │ │ │ │ └ ({'mask': 64, 'childOrSibling': [], 'childOrSiblingSelector': [], 'description': '全部删除'},)
│ │ │ │ └ 'objInfo'
│ │ │ └ <uiautomator2.base._BaseClient.jsonrpc.<locals>.JSONRpcWrapper object at 0x000001756719AA50>
│ │ └ <function BasicUiautomatorServer.jsonrpc_call at 0x0000017566B17C40>
│ └ <uiautomator2.Device object at 0x000001756358E510>
└ <uiautomator2.base._BaseClient.jsonrpc.<locals>.JSONRpcWrapper object at 0x000001756719AA50>
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\site-packages\uiautomator2\core.py", line 315, in jsonrpc_call
self.start_uiautomator()
│ └ <function BasicUiautomatorServer.start_uiautomator at 0x0000017566B177E0>
└ <uiautomator2.Device object at 0x000001756358E510>
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\site-packages\uiautomator2\core.py", line 231, in start_uiautomator
self._setup_jar()
│ └ <function BasicUiautomatorServer._setup_jar at 0x0000017566B17880>
└ <uiautomator2.Device object at 0x000001756358E510>
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\site-packages\uiautomator2\core.py", line 242, in _setup_jar
if self._check_device_file_hash(jar_path, target_path):
│ │ │ └ '/data/local/tmp/u2.jar'
│ │ └ WindowsPath('C:/Users/cuish/anaconda3/envs/xhs/Lib/site-packages/uiautomator2/assets/u2.jar')
│ └ <function BasicUiautomatorServer._check_device_file_hash at 0x0000017566B17920>
└ <uiautomator2.Device object at 0x000001756358E510>
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\site-packages\uiautomator2\core.py", line 255, in _check_device_file_hash
output = self._dev.shell(["toybox", "md5sum", remote_file])
│ │ │ └ '/data/local/tmp/u2.jar'
│ │ └ <function BaseDevice.shell at 0x0000017565E01BC0>
│ └ AdbDevice(serial=172.20.1.25:5555)
└ <uiautomator2.Device object at 0x000001756358E510>
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\site-packages\adbutils\_device_base.py", line 252, in shell
c = self.open_shell(cmdargs)
│ │ └ 'toybox md5sum /data/local/tmp/u2.jar'
│ └ <function BaseDevice.open_shell at 0x0000017565E01800>
└ AdbDevice(serial=172.20.1.25:5555)
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\site-packages\adbutils\_device_base.py", line 175, in open_shell
c = self.open_transport()
│ └ <function BaseDevice.open_transport at 0x0000017565E011C0>
└ AdbDevice(serial=172.20.1.25:5555)
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\site-packages\adbutils\_device_base.py", line 92, in open_transport
c.check_okay()
│ └ <function AdbConnection.check_okay at 0x0000017565D6A3E0>
└ <adbutils._adb.AdbConnection object at 0x000001756720E9F0>
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\site-packages\adbutils\_adb.py", line 192, in check_okay
raise AdbError(self.read_string_block())
│ │ └ <function AdbConnection.read_string_block at 0x0000017565D6A2A0>
│ └ <adbutils._adb.AdbConnection object at 0x000001756720E9F0>
└ <class 'adbutils.errors.AdbError'>
adbutils.errors.AdbError: device offline
2026-08-14 09:49:29.538 | SUCCESS | __mp_main__:human_like_scroll:253 - xhs_app:172.20.1.44 user_id -> 59c12e4150c4b45e2db6fff1 spider_count -> 4
2026-08-14 09:49:31.453 | SUCCESS | __mp_main__:human_like_scroll:253 - xhs_app:172.20.1.44 user_id -> 59c12e4150c4b45e2db6fff1 spider_count -> 5
2026-08-14 09:49:34.339 | SUCCESS | __mp_main__:human_like_scroll:253 - xhs_app:172.20.1.44 user_id -> 59c12e4150c4b45e2db6fff1 spider_count -> 5
2026-08-14 09:49:35.650 | SUCCESS | __mp_main__:human_like_scroll:253 - xhs_app:172.20.1.44 user_id -> 59c12e4150c4b45e2db6fff1 spider_count -> 5
2026-08-14 09:49:37.679 | SUCCESS | __mp_main__:wait_until_online:732 - 172.20.1.25:5555 ADB 已连续稳定 5 秒(端口 5037)
2026-08-14 09:49:38.586 | SUCCESS | __mp_main__:human_like_scroll:253 - xhs_app:172.20.1.44 user_id -> 59c12e4150c4b45e2db6fff1 spider_count -> 6
2026-08-14 09:49:42.875 | SUCCESS | __mp_main__:human_like_scroll:253 - xhs_app:172.20.1.44 user_id -> 59c12e4150c4b45e2db6fff1 spider_count -> 6
2026-08-14 09:49:44.567 | SUCCESS | __mp_main__:check_status:562 - com.xingin.alioth.search.GlobalSearchActivity
2026-08-14 09:49:44.567 | SUCCESS | __mp_main__:worker:918 - 172.20.1.25 当前搜索用户:6846395e000000001d026d76 42275720349
2026-08-14 09:49:45.545 | SUCCESS | __mp_main__:check_status:562 - com.xingin.alioth.search.GlobalSearchActivity
2026-08-14 09:49:45.546 | SUCCESS | __mp_main__:_search_user_id_first:499 - 先使用 user_id 搜索达人: 6846395e000000001d026d76
2026-08-14 09:49:46.197 | SUCCESS | __mp_main__:_open_search_input:385 - 清空上次搜索内容
2026-08-14 09:49:48.229 | ERROR | __mp_main__:worker:931 - 172.20.1.25 ADB 状态异常(offline),准备重建当前手机会话
Traceback (most recent call last):
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\site-packages\uiautomator2\base.py", line 111, in shell
ret = self._dev.shell2(cmdargs, timeout=timeout)
│ │ │ │ └ 60
│ │ │ └ ['am', 'broadcast', '-a', 'ADB_KEYBOARD_INPUT_TEXT', '--es', 'text', 'Njg0NjM5NWUwMDAwMDAwMDFkMDI2ZDc2']
│ │ └ <function BaseDevice.shell2 at 0x0000017565E01EE0>
│ └ AdbDevice(serial=172.20.1.25:5555)
└ <uiautomator2.Device object at 0x000001756718E990>
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\site-packages\adbutils\_device_base.py", line 334, in shell2
result = self._shell_v1(cmdargs, timeout)
│ │ │ └ 60
│ │ └ 'am broadcast -a ADB_KEYBOARD_INPUT_TEXT --es text Njg0NjM5NWUwMDAwMDAwMDFkMDI2ZDc2'
│ └ <function BaseDevice._shell_v1 at 0x0000017565E01F80>
└ AdbDevice(serial=172.20.1.25:5555)
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\site-packages\adbutils\_device_base.py", line 357, in _shell_v1
raise AdbError("shell output invalid", newcmd, output)
│ │ └ b'Broadcasting: Intent { act=ADB_KEYBOARD_INPUT_TEXT flg=0x400000 (has extras) }\n'
│ └ 'am broadcast -a ADB_KEYBOARD_INPUT_TEXT --es text Njg0NjM5NWUwMDAwMDAwMDFkMDI2ZDc2; echo X4EXIT:$?'
└ <class 'adbutils.errors.AdbError'>
adbutils.errors.AdbError: ('shell output invalid', 'am broadcast -a ADB_KEYBOARD_INPUT_TEXT --es text Njg0NjM5NWUwMDAwMDAwMDFkMDI2ZDc2; echo X4EXIT:$?', b'Broadcasting: Intent { act=ADB_KEYBOARD_INPUT_TEXT flg=0x400000 (has extras) }\n')
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\multiprocessing\spawn.py", line 122, in spawn_main
exitcode = _main(fd, parent_sentinel)
│ │ └ 340
│ └ 3
└ <function _main at 0x0000017563AE1080>
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\multiprocessing\spawn.py", line 135, in _main
return self._bootstrap(parent_sentinel)
│ │ └ 340
│ └ <function BaseProcess._bootstrap at 0x00000175637E6E80>
└ <Process name='Process-2' parent=16452 started>
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\multiprocessing\process.py", line 313, in _bootstrap
self.run()
│ └ <function BaseProcess.run at 0x0000017563794CC0>
└ <Process name='Process-2' parent=16452 started>
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\multiprocessing\process.py", line 108, in run
self._target(*self._args, **self._kwargs)
│ │ │ │ │ └ {}
│ │ │ │ └ <Process name='Process-2' parent=16452 started>
│ │ │ └ ('172.20.1.25', 1)
│ │ └ <Process name='Process-2' parent=16452 started>
│ └ <function worker at 0x00000175671FD080>
└ <Process name='Process-2' parent=16452 started>
> File "C:\Users\cuish\auto_xhs\xhs_auto_app_search_user.py", line 919, in worker
auto_operation(d, user_id, red_id, client_ip)
│ │ │ │ └ '172.20.1.25'
│ │ │ └ '42275720349'
│ │ └ '6846395e000000001d026d76'
│ └ <uiautomator2.Device object at 0x000001756718E990>
└ <function auto_operation at 0x00000175671FCFE0>
File "C:\Users\cuish\auto_xhs\xhs_auto_app_search_user.py", line 877, in auto_operation
do_search_scroll(d, user_id, red_id, client_ip)
│ │ │ │ └ '172.20.1.25'
│ │ │ └ '42275720349'
│ │ └ '6846395e000000001d026d76'
│ └ <uiautomator2.Device object at 0x000001756718E990>
└ <function do_search_scroll at 0x00000175671FC4A0>
File "C:\Users\cuish\auto_xhs\xhs_auto_app_search_user.py", line 520, in do_search_scroll
if _search_user_id_first(d, user_id, red_id, client_ip):
│ │ │ │ └ '172.20.1.25'
│ │ │ └ '42275720349'
│ │ └ '6846395e000000001d026d76'
│ └ <uiautomator2.Device object at 0x000001756718E990>
└ <function _search_user_id_first at 0x00000175671FC400>
File "C:\Users\cuish\auto_xhs\xhs_auto_app_search_user.py", line 500, in _search_user_id_first
if not _input_and_submit_search(d, user_id):
│ │ └ '6846395e000000001d026d76'
│ └ <uiautomator2.Device object at 0x000001756718E990>
└ <function _input_and_submit_search at 0x00000175671FC180>
File "C:\Users\cuish\auto_xhs\xhs_auto_app_search_user.py", line 416, in _input_and_submit_search
d.send_keys(keyword)
│ │ └ '6846395e000000001d026d76'
│ └ <function Device.send_keys at 0x0000017566B53100>
└ <uiautomator2.Device object at 0x000001756718E990>
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\site-packages\uiautomator2\__init__.py", line 883, in send_keys
InputMethodMixIn.send_keys(self, text)
│ │ │ └ '6846395e000000001d026d76'
│ │ └ <uiautomator2.Device object at 0x000001756718E990>
│ └ <function InputMethodMixIn.send_keys at 0x0000017566B0FF60>
└ <class 'uiautomator2._input.InputMethodMixIn'>
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\site-packages\uiautomator2\_input.py", line 113, in send_keys
self._must_broadcast(cmd, {"text": base64text})
│ │ │ └ 'Njg0NjM5NWUwMDAwMDAwMDFkMDI2ZDc2'
│ │ └ 'ADB_KEYBOARD_INPUT_TEXT'
│ └ <function InputMethodMixIn._must_broadcast at 0x0000017566B140E0>
└ <uiautomator2.Device object at 0x000001756718E990>
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\site-packages\decorator.py", line 235, in fun
return caller(func, *(extras + args), **kw)
│ │ │ │ └ {}
│ │ │ └ (<uiautomator2.Device object at 0x000001756718E990>, 'ADB_KEYBOARD_INPUT_TEXT', {'text': 'Njg0NjM5NWUwMDAwMDAwMDFkMDI2ZDc2'})
│ │ └ ()
│ └ <function InputMethodMixIn._must_broadcast at 0x0000017566B0FEC0>
└ <function retry.<locals>.retry_decorator at 0x0000017566B0FE20>
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\site-packages\retry\api.py", line 90, in retry_decorator
return __retry_internal(partial(f, *args, **kwargs), exceptions, tries, delay, max_delay, backoff, jitter,
│ │ │ │ │ │ │ │ │ │ └ 0.5
│ │ │ │ │ │ │ │ │ └ 1
│ │ │ │ │ │ │ │ └ None
│ │ │ │ │ │ │ └ 1
│ │ │ │ │ │ └ 3
│ │ │ │ │ └ <class 'uiautomator2.exceptions.AdbBroadcastError'>
│ │ │ │ └ {}
│ │ │ └ (<uiautomator2.Device object at 0x000001756718E990>, 'ADB_KEYBOARD_INPUT_TEXT', {'text': 'Njg0NjM5NWUwMDAwMDAwMDFkMDI2ZDc2'})
│ │ └ <function InputMethodMixIn._must_broadcast at 0x0000017566B0FEC0>
│ └ <class 'functools.partial'>
└ <function __retry_internal at 0x0000017566A18540>
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\site-packages\retry\api.py", line 35, in __retry_internal
return f()
└ functools.partial(<function InputMethodMixIn._must_broadcast at 0x0000017566B0FEC0>, <uiautomator2.Device object at 0x0000017...
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\site-packages\uiautomator2\_input.py", line 103, in _must_broadcast
result = self._broadcast(action, extras)
│ │ │ └ {'text': 'Njg0NjM5NWUwMDAwMDAwMDFkMDI2ZDc2'}
│ │ └ 'ADB_KEYBOARD_INPUT_TEXT'
│ └ <function InputMethodMixIn._broadcast at 0x0000017566B0FD80>
└ <uiautomator2.Device object at 0x000001756718E990>
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\site-packages\uiautomator2\_input.py", line 94, in _broadcast
output = self.shell(args).output
│ │ └ ['am', 'broadcast', '-a', 'ADB_KEYBOARD_INPUT_TEXT', '--es', 'text', 'Njg0NjM5NWUwMDAwMDAwMDFkMDI2ZDc2']
│ └ <function _BaseClient.shell at 0x0000017566B46200>
└ <uiautomator2.Device object at 0x000001756718E990>
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\site-packages\uiautomator2\base.py", line 114, in shell
raise AdbShellError(e)
└ <class 'uiautomator2.exceptions.AdbShellError'>
uiautomator2.exceptions.AdbShellError: ('shell output invalid', 'am broadcast -a ADB_KEYBOARD_INPUT_TEXT --es text Njg0NjM5NWUwMDAwMDAwMDFkMDI2ZDc2; echo X4EXIT:$?', b'Broadcasting: Intent { act=ADB_KEYBOARD_INPUT_TEXT flg=0x400000 (has extras) }\n')
2026-08-14 09:49:51.551 | SUCCESS | __mp_main__:human_like_scroll:253 - xhs_app:172.20.1.44 user_id -> 59c12e4150c4b45e2db6fff1 spider_count -> 6
2026-08-14 09:49:53.825 | SUCCESS | __mp_main__:human_like_scroll:253 - xhs_app:172.20.1.44 user_id -> 59c12e4150c4b45e2db6fff1 spider_count -> 6
2026-08-14 09:49:54.779 | SUCCESS | __mp_main__:human_like_scroll:253 - xhs_app:172.20.1.44 user_id -> 59c12e4150c4b45e2db6fff1 spider_count -> 7
2026-08-14 09:49:57.334 | SUCCESS | __mp_main__:wait_until_online:732 - 172.20.1.25:5555 ADB 已连续稳定 5 秒(端口 5037)
2026-08-14 09:49:57.896 | SUCCESS | __mp_main__:human_like_scroll:253 - xhs_app:172.20.1.44 user_id -> 59c12e4150c4b45e2db6fff1 spider_count -> 7
2026-08-14 09:50:00.271 | SUCCESS | __mp_main__:human_like_scroll:253 - xhs_app:172.20.1.44 user_id -> 59c12e4150c4b45e2db6fff1 spider_count -> 7
2026-08-14 09:50:04.281 | SUCCESS | __mp_main__:check_status:562 - com.xingin.alioth.search.GlobalSearchActivity
2026-08-14 09:50:04.282 | SUCCESS | __mp_main__:worker:918 - 172.20.1.25 当前搜索用户:6846395e000000001d026d76 42275720349
2026-08-14 09:50:05.301 | SUCCESS | __mp_main__:check_status:562 - com.xingin.alioth.search.GlobalSearchActivity
2026-08-14 09:50:05.301 | SUCCESS | __mp_main__:_search_user_id_first:499 - 先使用 user_id 搜索达人: 6846395e000000001d026d76
2026-08-14 09:50:05.852 | SUCCESS | __mp_main__:_open_search_input:385 - 清空上次搜索内容
2026-08-14 09:50:07.547 | ERROR | __mp_main__:worker:931 - 172.20.1.25 ADB 状态异常(offline),准备重建当前手机会话
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\multiprocessing\spawn.py", line 122, in spawn_main
exitcode = _main(fd, parent_sentinel)
│ │ └ 340
│ └ 3
└ <function _main at 0x0000017563AE1080>
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\multiprocessing\spawn.py", line 135, in _main
return self._bootstrap(parent_sentinel)
│ │ └ 340
│ └ <function BaseProcess._bootstrap at 0x00000175637E6E80>
└ <Process name='Process-2' parent=16452 started>
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\multiprocessing\process.py", line 313, in _bootstrap
self.run()
│ └ <function BaseProcess.run at 0x0000017563794CC0>
└ <Process name='Process-2' parent=16452 started>
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\multiprocessing\process.py", line 108, in run
self._target(*self._args, **self._kwargs)
│ │ │ │ │ └ {}
│ │ │ │ └ <Process name='Process-2' parent=16452 started>
│ │ │ └ ('172.20.1.25', 1)
│ │ └ <Process name='Process-2' parent=16452 started>
│ └ <function worker at 0x00000175671FD080>
└ <Process name='Process-2' parent=16452 started>
> File "C:\Users\cuish\auto_xhs\xhs_auto_app_search_user.py", line 919, in worker
auto_operation(d, user_id, red_id, client_ip)
│ │ │ │ └ '172.20.1.25'
│ │ │ └ '42275720349'
│ │ └ '6846395e000000001d026d76'
│ └ <uiautomator2.Device object at 0x000001756718EE90>
└ <function auto_operation at 0x00000175671FCFE0>
File "C:\Users\cuish\auto_xhs\xhs_auto_app_search_user.py", line 877, in auto_operation
do_search_scroll(d, user_id, red_id, client_ip)
│ │ │ │ └ '172.20.1.25'
│ │ │ └ '42275720349'
│ │ └ '6846395e000000001d026d76'
│ └ <uiautomator2.Device object at 0x000001756718EE90>
└ <function do_search_scroll at 0x00000175671FC4A0>
File "C:\Users\cuish\auto_xhs\xhs_auto_app_search_user.py", line 520, in do_search_scroll
if _search_user_id_first(d, user_id, red_id, client_ip):
│ │ │ │ └ '172.20.1.25'
│ │ │ └ '42275720349'
│ │ └ '6846395e000000001d026d76'
│ └ <uiautomator2.Device object at 0x000001756718EE90>
└ <function _search_user_id_first at 0x00000175671FC400>
File "C:\Users\cuish\auto_xhs\xhs_auto_app_search_user.py", line 500, in _search_user_id_first
if not _input_and_submit_search(d, user_id):
│ │ └ '6846395e000000001d026d76'
│ └ <uiautomator2.Device object at 0x000001756718EE90>
└ <function _input_and_submit_search at 0x00000175671FC180>
File "C:\Users\cuish\auto_xhs\xhs_auto_app_search_user.py", line 408, in _input_and_submit_search
if not _open_search_input(d, current_keyword):
│ │ └ None
│ └ <uiautomator2.Device object at 0x000001756718EE90>
└ <function _open_search_input at 0x00000175671FC0E0>
File "C:\Users\cuish\auto_xhs\xhs_auto_app_search_user.py", line 396, in _open_search_input
d(text="搜索, ").click()
└ <uiautomator2.Device object at 0x000001756718EE90>
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\site-packages\uiautomator2\_selector.py", line 151, in click
self.session.click(x, y)
│ │ │ │ └ 160.5
│ │ │ └ 435.0
│ │ └ <function _Device.click at 0x0000017566B50900>
│ └ <uiautomator2.Device object at 0x000001756718EE90>
└ <uiautomator2._selector.UiObject object at 0x000001756727B530>
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\site-packages\uiautomator2\__init__.py", line 226, in click
self.jsonrpc.click(x, y)
│ │ │ └ 160.5
│ │ └ 435.0
│ └ <property object at 0x0000017566B40F40>
└ <uiautomator2.Device object at 0x000001756718EE90>
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\site-packages\uiautomator2\base.py", line 158, in __call__
return self.server.jsonrpc_call(self.method, params, http_timeout)
│ │ │ │ │ │ └ 300
│ │ │ │ │ └ (435.0, 160.5)
│ │ │ │ └ 'click'
│ │ │ └ <uiautomator2.base._BaseClient.jsonrpc.<locals>.JSONRpcWrapper object at 0x000001756719AA50>
│ │ └ <function BasicUiautomatorServer.jsonrpc_call at 0x0000017566B17C40>
│ └ <uiautomator2.Device object at 0x000001756718EE90>
└ <uiautomator2.base._BaseClient.jsonrpc.<locals>.JSONRpcWrapper object at 0x000001756719AA50>
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\site-packages\uiautomator2\core.py", line 311, in jsonrpc_call
return _jsonrpc_call(self._dev, self._device_server_port, method, params, timeout, self._debug)
│ │ │ │ │ │ │ │ │ └ False
│ │ │ │ │ │ │ │ └ <uiautomator2.Device object at 0x000001756718EE90>
│ │ │ │ │ │ │ └ 300
│ │ │ │ │ │ └ (435.0, 160.5)
│ │ │ │ │ └ 'click'
│ │ │ │ └ 9008
│ │ │ └ <uiautomator2.Device object at 0x000001756718EE90>
│ │ └ AdbDevice(serial=172.20.1.25:5555)
│ └ <uiautomator2.Device object at 0x000001756718EE90>
└ <function _jsonrpc_call at 0x0000017566B174C0>
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\site-packages\uiautomator2\core.py", line 174, in _jsonrpc_call
data = r.json()
│ └ <function HTTPResponse.json at 0x0000017566B16FC0>
└ <uiautomator2.core.HTTPResponse object at 0x0000017567284820>
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\site-packages\uiautomator2\core.py", line 82, in json
return json.loads(self.content)
│ │ │ └ bytearray(b'')
│ │ └ <uiautomator2.core.HTTPResponse object at 0x0000017567284820>
│ └ <function loads at 0x0000017565C51260>
└ <module 'json' from 'C:\\Users\\cuish\\anaconda3\\envs\\xhs\\Lib\\json\\__init__.py'>
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\json\__init__.py", line 352, in loads
return _default_decoder.decode(s)
│ │ └ ''
│ └ <function JSONDecoder.decode at 0x0000017565C50AE0>
└ <json.decoder.JSONDecoder object at 0x0000017565BA6120>
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\json\decoder.py", line 345, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
│ │ │ │ └ ''
│ │ │ └ <built-in method match of re.Pattern object at 0x0000017565C21490>
│ │ └ ''
│ └ <function JSONDecoder.raw_decode at 0x0000017565C50B80>
└ <json.decoder.JSONDecoder object at 0x0000017565BA6120>
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\json\decoder.py", line 363, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
│ └ ''
└ <class 'json.decoder.JSONDecodeError'>
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
2026-08-14 09:50:09.121 | SUCCESS | __mp_main__:human_like_scroll:253 - xhs_app:172.20.1.44 user_id -> 59c12e4150c4b45e2db6fff1 spider_count -> 7
2026-08-14 09:50:11.560 | SUCCESS | __mp_main__:human_like_scroll:253 - xhs_app:172.20.1.44 user_id -> 59c12e4150c4b45e2db6fff1 spider_count -> 8
2026-08-14 09:50:13.791 | SUCCESS | __mp_main__:human_like_scroll:253 - xhs_app:172.20.1.44 user_id -> 59c12e4150c4b45e2db6fff1 spider_count -> 8
2026-08-14 09:50:15.738 | SUCCESS | __mp_main__:human_like_scroll:253 - xhs_app:172.20.1.44 user_id -> 59c12e4150c4b45e2db6fff1 spider_count -> 8
2026-08-14 09:50:16.680 | SUCCESS | __mp_main__:wait_until_online:732 - 172.20.1.25:5555 ADB 已连续稳定 5 秒(端口 5037)
2026-08-14 09:50:17.806 | SUCCESS | __mp_main__:human_like_scroll:253 - xhs_app:172.20.1.44 user_id -> 59c12e4150c4b45e2db6fff1 spider_count -> 8
2026-08-14 09:50:20.128 | SUCCESS | __mp_main__:human_like_scroll:253 - xhs_app:172.20.1.44 user_id -> 59c12e4150c4b45e2db6fff1 spider_count -> 8
2026-08-14 09:50:22.056 | SUCCESS | __mp_main__:human_like_scroll:253 - xhs_app:172.20.1.44 user_id -> 59c12e4150c4b45e2db6fff1 spider_count -> 8
2026-08-14 09:50:23.603 | SUCCESS | __mp_main__:check_status:562 - com.xingin.alioth.search.GlobalSearchActivity
2026-08-14 09:50:23.604 | SUCCESS | __mp_main__:worker:918 - 172.20.1.25 当前搜索用户:6846395e000000001d026d76 42275720349
2026-08-14 09:50:23.890 | SUCCESS | __mp_main__:human_like_scroll:253 - xhs_app:172.20.1.44 user_id -> 59c12e4150c4b45e2db6fff1 spider_count -> 8
2026-08-14 09:50:24.545 | SUCCESS | __mp_main__:check_status:562 - com.xingin.alioth.search.GlobalSearchActivity
2026-08-14 09:50:24.545 | SUCCESS | __mp_main__:_search_user_id_first:499 - 先使用 user_id 搜索达人: 6846395e000000001d026d76
2026-08-14 09:50:25.179 | SUCCESS | __mp_main__:_open_search_input:385 - 清空上次搜索内容
2026-08-14 09:50:25.308 | SUCCESS | __mp_main__:human_like_scroll:253 - xhs_app:172.20.1.44 user_id -> 59c12e4150c4b45e2db6fff1 spider_count -> 9
2026-08-14 09:50:26.563 | ERROR | __mp_main__:worker:931 - 172.20.1.25 ADB 状态异常(offline),准备重建当前手机会话
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\multiprocessing\spawn.py", line 122, in spawn_main
exitcode = _main(fd, parent_sentinel)
│ │ └ 340
│ └ 3
└ <function _main at 0x0000017563AE1080>
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\multiprocessing\spawn.py", line 135, in _main
return self._bootstrap(parent_sentinel)
│ │ └ 340
│ └ <function BaseProcess._bootstrap at 0x00000175637E6E80>
└ <Process name='Process-2' parent=16452 started>
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\multiprocessing\process.py", line 313, in _bootstrap
self.run()
│ └ <function BaseProcess.run at 0x0000017563794CC0>
└ <Process name='Process-2' parent=16452 started>
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\multiprocessing\process.py", line 108, in run
self._target(*self._args, **self._kwargs)
│ │ │ │ │ └ {}
│ │ │ │ └ <Process name='Process-2' parent=16452 started>
│ │ │ └ ('172.20.1.25', 1)
│ │ └ <Process name='Process-2' parent=16452 started>
│ └ <function worker at 0x00000175671FD080>
└ <Process name='Process-2' parent=16452 started>
> File "C:\Users\cuish\auto_xhs\xhs_auto_app_search_user.py", line 919, in worker
auto_operation(d, user_id, red_id, client_ip)
│ │ │ │ └ '172.20.1.25'
│ │ │ └ '42275720349'
│ │ └ '6846395e000000001d026d76'
│ └ <uiautomator2.Device object at 0x00000175671EDBA0>
└ <function auto_operation at 0x00000175671FCFE0>
File "C:\Users\cuish\auto_xhs\xhs_auto_app_search_user.py", line 877, in auto_operation
do_search_scroll(d, user_id, red_id, client_ip)
│ │ │ │ └ '172.20.1.25'
│ │ │ └ '42275720349'
│ │ └ '6846395e000000001d026d76'
│ └ <uiautomator2.Device object at 0x00000175671EDBA0>
└ <function do_search_scroll at 0x00000175671FC4A0>
File "C:\Users\cuish\auto_xhs\xhs_auto_app_search_user.py", line 520, in do_search_scroll
if _search_user_id_first(d, user_id, red_id, client_ip):
│ │ │ │ └ '172.20.1.25'
│ │ │ └ '42275720349'
│ │ └ '6846395e000000001d026d76'
│ └ <uiautomator2.Device object at 0x00000175671EDBA0>
└ <function _search_user_id_first at 0x00000175671FC400>
File "C:\Users\cuish\auto_xhs\xhs_auto_app_search_user.py", line 500, in _search_user_id_first
if not _input_and_submit_search(d, user_id):
│ │ └ '6846395e000000001d026d76'
│ └ <uiautomator2.Device object at 0x00000175671EDBA0>
└ <function _input_and_submit_search at 0x00000175671FC180>
File "C:\Users\cuish\auto_xhs\xhs_auto_app_search_user.py", line 408, in _input_and_submit_search
if not _open_search_input(d, current_keyword):
│ │ └ None
│ └ <uiautomator2.Device object at 0x00000175671EDBA0>
└ <function _open_search_input at 0x00000175671FC0E0>
File "C:\Users\cuish\auto_xhs\xhs_auto_app_search_user.py", line 396, in _open_search_input
d(text="搜索, ").click()
└ <uiautomator2.Device object at 0x00000175671EDBA0>
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\site-packages\uiautomator2\_selector.py", line 150, in click
x, y = self.center(offset=offset)
│ │ └ None
│ └ <function UiObject.center at 0x0000017566B15300>
└ <uiautomator2._selector.UiObject object at 0x000001756729F830>
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\site-packages\uiautomator2\_selector.py", line 171, in center
lx, ly, rx, ry = self.bounds()
│ └ <function UiObject.bounds at 0x0000017566B15260>
└ <uiautomator2._selector.UiObject object at 0x000001756729F830>
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\site-packages\uiautomator2\_selector.py", line 158, in bounds
info = self.info
│ └ <property object at 0x0000017566AD1580>
└ <uiautomator2._selector.UiObject object at 0x000001756729F830>
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\site-packages\uiautomator2\_selector.py", line 128, in info
return self.jsonrpc.objInfo(self.selector)
│ │ │ └ {'mask': 1, 'childOrSibling': [], 'childOrSiblingSelector': [], 'text': '搜索, '}
│ │ └ <uiautomator2._selector.UiObject object at 0x000001756729F830>
│ └ <uiautomator2.base._BaseClient.jsonrpc.<locals>.JSONRpcWrapper object at 0x000001756719AE40>
└ <uiautomator2._selector.UiObject object at 0x000001756729F830>
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\site-packages\uiautomator2\base.py", line 158, in __call__
return self.server.jsonrpc_call(self.method, params, http_timeout)
│ │ │ │ │ │ └ 300
│ │ │ │ │ └ ({'mask': 1, 'childOrSibling': [], 'childOrSiblingSelector': [], 'text': '搜索, '},)
│ │ │ │ └ 'objInfo'
│ │ │ └ <uiautomator2.base._BaseClient.jsonrpc.<locals>.JSONRpcWrapper object at 0x000001756719AE40>
│ │ └ <function BasicUiautomatorServer.jsonrpc_call at 0x0000017566B17C40>
│ └ <uiautomator2.Device object at 0x00000175671EDBA0>
└ <uiautomator2.base._BaseClient.jsonrpc.<locals>.JSONRpcWrapper object at 0x000001756719AE40>
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\site-packages\uiautomator2\core.py", line 311, in jsonrpc_call
return _jsonrpc_call(self._dev, self._device_server_port, method, params, timeout, self._debug)
│ │ │ │ │ │ │ │ │ └ False
│ │ │ │ │ │ │ │ └ <uiautomator2.Device object at 0x00000175671EDBA0>
│ │ │ │ │ │ │ └ 300
│ │ │ │ │ │ └ ({'mask': 1, 'childOrSibling': [], 'childOrSiblingSelector': [], 'text': '搜索, '},)
│ │ │ │ │ └ 'objInfo'
│ │ │ │ └ 9008
│ │ │ └ <uiautomator2.Device object at 0x00000175671EDBA0>
│ │ └ AdbDevice(serial=172.20.1.25:5555)
│ └ <uiautomator2.Device object at 0x00000175671EDBA0>
└ <function _jsonrpc_call at 0x0000017566B174C0>
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\site-packages\uiautomator2\core.py", line 173, in _jsonrpc_call
r = _http_request(dev, device_port, "POST", "/jsonrpc/0", payload, timeout=timeout, print_request=print_request)
│ │ │ │ │ └ False
│ │ │ │ └ 300
│ │ │ └ {'jsonrpc': '2.0', 'id': 1, 'method': 'objInfo', 'params': ({'mask': 1, 'childOrSibling': [], 'childOrSiblingSelector': [], '...
│ │ └ 9008
│ └ AdbDevice(serial=172.20.1.25:5555)
└ <function _http_request at 0x0000017566B17380>
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\site-packages\uiautomator2\core.py", line 140, in _http_request
_response = conn.getresponse()
│ └ <function HTTPConnection.getresponse at 0x0000017565E3E700>
└ <uiautomator2.core.AdbHTTPConnection object at 0x0000017567172430>
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\http\client.py", line 1450, in getresponse
response.begin()
│ └ <function HTTPResponse.begin at 0x0000017565E3C5E0>
└ <http.client.HTTPResponse object at 0x0000017567009AE0>
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\http\client.py", line 336, in begin
version, status, reason = self._read_status()
│ └ <function HTTPResponse._read_status at 0x0000017565E3C540>
└ <http.client.HTTPResponse object at 0x0000017567009AE0>
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\http\client.py", line 305, in _read_status
raise RemoteDisconnected("Remote end closed connection without"
└ <class 'http.client.RemoteDisconnected'>
http.client.RemoteDisconnected: Remote end closed connection without response
2026-08-14 09:50:28.238 | SUCCESS | __mp_main__:human_like_scroll:253 - xhs_app:172.20.1.44 user_id -> 59c12e4150c4b45e2db6fff1 spider_count -> 9
2026-08-14 09:50:29.832 | SUCCESS | __mp_main__:human_like_scroll:253 - xhs_app:172.20.1.44 user_id -> 59c12e4150c4b45e2db6fff1 spider_count -> 9
2026-08-14 09:50:33.058 | SUCCESS | __mp_main__:human_like_scroll:253 - xhs_app:172.20.1.44 user_id -> 59c12e4150c4b45e2db6fff1 spider_count -> 10
2026-08-14 09:50:34.413 | SUCCESS | __mp_main__:human_like_scroll:253 - xhs_app:172.20.1.44 user_id -> 59c12e4150c4b45e2db6fff1 spider_count -> 10
2026-08-14 09:50:35.465 | SUCCESS | __mp_main__:human_like_scroll:253 - xhs_app:172.20.1.44 user_id -> 59c12e4150c4b45e2db6fff1 spider_count -> 10
2026-08-14 09:50:35.673 | SUCCESS | __mp_main__:wait_until_online:732 - 172.20.1.25:5555 ADB 已连续稳定 5 秒(端口 5037)
2026-08-14 09:50:42.938 | SUCCESS | __mp_main__:check_status:562 - com.xingin.alioth.search.GlobalSearchActivity
2026-08-14 09:50:42.938 | SUCCESS | __mp_main__:worker:918 - 172.20.1.25 当前搜索用户:6846395e000000001d026d76 42275720349
2026-08-14 09:50:43.540 | SUCCESS | __mp_main__:human_like_scroll:253 - xhs_app:172.20.1.44 user_id -> 59c12e4150c4b45e2db6fff1 spider_count -> 11
2026-08-14 09:50:43.932 | SUCCESS | __mp_main__:check_status:562 - com.xingin.alioth.search.GlobalSearchActivity
2026-08-14 09:50:43.932 | SUCCESS | __mp_main__:_search_user_id_first:499 - 先使用 user_id 搜索达人: 6846395e000000001d026d76
2026-08-14 09:50:45.258 | ERROR | __mp_main__:worker:931 - 172.20.1.25 ADB 状态异常(offline),准备重建当前手机会话
Traceback (most recent call last):
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\site-packages\uiautomator2\base.py", line 111, in shell
ret = self._dev.shell2(cmdargs, timeout=timeout)
│ │ │ │ └ 60
│ │ │ └ ['am', 'broadcast', '-a', 'ADB_KEYBOARD_HIDE']
│ │ └ <function BaseDevice.shell2 at 0x0000017565E01EE0>
│ └ AdbDevice(serial=172.20.1.25:5555)
└ <uiautomator2.Device object at 0x00000175671EDF30>
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\site-packages\adbutils\_device_base.py", line 334, in shell2
result = self._shell_v1(cmdargs, timeout)
│ │ │ └ 60
│ │ └ 'am broadcast -a ADB_KEYBOARD_HIDE'
│ └ <function BaseDevice._shell_v1 at 0x0000017565E01F80>
└ AdbDevice(serial=172.20.1.25:5555)
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\site-packages\adbutils\_device_base.py", line 354, in _shell_v1
output: bytes = self.shell(newcmd, timeout=timeout, encoding=None, rstrip=False) # type: ignore
│ │ │ └ 60
│ │ └ 'am broadcast -a ADB_KEYBOARD_HIDE; echo X4EXIT:$?'
│ └ <function BaseDevice.shell at 0x0000017565E01BC0>
└ AdbDevice(serial=172.20.1.25:5555)
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\site-packages\adbutils\_device_base.py", line 252, in shell
c = self.open_shell(cmdargs)
│ │ └ 'am broadcast -a ADB_KEYBOARD_HIDE; echo X4EXIT:$?'
│ └ <function BaseDevice.open_shell at 0x0000017565E01800>
└ AdbDevice(serial=172.20.1.25:5555)
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\site-packages\adbutils\_device_base.py", line 177, in open_shell
c.check_okay()
│ └ <function AdbConnection.check_okay at 0x0000017565D6A3E0>
└ <adbutils._adb.AdbConnection object at 0x000001756729FFB0>
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\site-packages\adbutils\_adb.py", line 192, in check_okay
raise AdbError(self.read_string_block())
│ │ └ <function AdbConnection.read_string_block at 0x0000017565D6A2A0>
│ └ <adbutils._adb.AdbConnection object at 0x000001756729FFB0>
└ <class 'adbutils.errors.AdbError'>
adbutils.errors.AdbError: closed
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\multiprocessing\spawn.py", line 122, in spawn_main
exitcode = _main(fd, parent_sentinel)
│ │ └ 340
│ └ 3
└ <function _main at 0x0000017563AE1080>
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\multiprocessing\spawn.py", line 135, in _main
return self._bootstrap(parent_sentinel)
│ │ └ 340
│ └ <function BaseProcess._bootstrap at 0x00000175637E6E80>
└ <Process name='Process-2' parent=16452 started>
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\multiprocessing\process.py", line 313, in _bootstrap
self.run()
│ └ <function BaseProcess.run at 0x0000017563794CC0>
└ <Process name='Process-2' parent=16452 started>
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\multiprocessing\process.py", line 108, in run
self._target(*self._args, **self._kwargs)
│ │ │ │ │ └ {}
│ │ │ │ └ <Process name='Process-2' parent=16452 started>
│ │ │ └ ('172.20.1.25', 1)
│ │ └ <Process name='Process-2' parent=16452 started>
│ └ <function worker at 0x00000175671FD080>
└ <Process name='Process-2' parent=16452 started>
> File "C:\Users\cuish\auto_xhs\xhs_auto_app_search_user.py", line 919, in worker
auto_operation(d, user_id, red_id, client_ip)
│ │ │ │ └ '172.20.1.25'
│ │ │ └ '42275720349'
│ │ └ '6846395e000000001d026d76'
│ └ <uiautomator2.Device object at 0x00000175671EDF30>
└ <function auto_operation at 0x00000175671FCFE0>
File "C:\Users\cuish\auto_xhs\xhs_auto_app_search_user.py", line 877, in auto_operation
do_search_scroll(d, user_id, red_id, client_ip)
│ │ │ │ └ '172.20.1.25'
│ │ │ └ '42275720349'
│ │ └ '6846395e000000001d026d76'
│ └ <uiautomator2.Device object at 0x00000175671EDF30>
└ <function do_search_scroll at 0x00000175671FC4A0>
File "C:\Users\cuish\auto_xhs\xhs_auto_app_search_user.py", line 520, in do_search_scroll
if _search_user_id_first(d, user_id, red_id, client_ip):
│ │ │ │ └ '172.20.1.25'
│ │ │ └ '42275720349'
│ │ └ '6846395e000000001d026d76'
│ └ <uiautomator2.Device object at 0x00000175671EDF30>
└ <function _search_user_id_first at 0x00000175671FC400>
File "C:\Users\cuish\auto_xhs\xhs_auto_app_search_user.py", line 500, in _search_user_id_first
if not _input_and_submit_search(d, user_id):
│ │ └ '6846395e000000001d026d76'
│ └ <uiautomator2.Device object at 0x00000175671EDF30>
└ <function _input_and_submit_search at 0x00000175671FC180>
File "C:\Users\cuish\auto_xhs\xhs_auto_app_search_user.py", line 416, in _input_and_submit_search
d.send_keys(keyword)
│ │ └ '6846395e000000001d026d76'
│ └ <function Device.send_keys at 0x0000017566B53100>
└ <uiautomator2.Device object at 0x00000175671EDF30>
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\site-packages\uiautomator2\__init__.py", line 883, in send_keys
InputMethodMixIn.send_keys(self, text)
│ │ │ └ '6846395e000000001d026d76'
│ │ └ <uiautomator2.Device object at 0x00000175671EDF30>
│ └ <function InputMethodMixIn.send_keys at 0x0000017566B0FF60>
└ <class 'uiautomator2._input.InputMethodMixIn'>
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\site-packages\uiautomator2\_input.py", line 115, in send_keys
self._must_broadcast('ADB_KEYBOARD_HIDE')
│ └ <function InputMethodMixIn._must_broadcast at 0x0000017566B140E0>
└ <uiautomator2.Device object at 0x00000175671EDF30>
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\site-packages\decorator.py", line 235, in fun
return caller(func, *(extras + args), **kw)
│ │ │ │ └ {}
│ │ │ └ (<uiautomator2.Device object at 0x00000175671EDF30>, 'ADB_KEYBOARD_HIDE', {})
│ │ └ ()
│ └ <function InputMethodMixIn._must_broadcast at 0x0000017566B0FEC0>
└ <function retry.<locals>.retry_decorator at 0x0000017566B0FE20>
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\site-packages\retry\api.py", line 90, in retry_decorator
return __retry_internal(partial(f, *args, **kwargs), exceptions, tries, delay, max_delay, backoff, jitter,
│ │ │ │ │ │ │ │ │ │ └ 0.5
│ │ │ │ │ │ │ │ │ └ 1
│ │ │ │ │ │ │ │ └ None
│ │ │ │ │ │ │ └ 1
│ │ │ │ │ │ └ 3
│ │ │ │ │ └ <class 'uiautomator2.exceptions.AdbBroadcastError'>
│ │ │ │ └ {}
│ │ │ └ (<uiautomator2.Device object at 0x00000175671EDF30>, 'ADB_KEYBOARD_HIDE', {})
│ │ └ <function InputMethodMixIn._must_broadcast at 0x0000017566B0FEC0>
│ └ <class 'functools.partial'>
└ <function __retry_internal at 0x0000017566A18540>
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\site-packages\retry\api.py", line 35, in __retry_internal
return f()
└ functools.partial(<function InputMethodMixIn._must_broadcast at 0x0000017566B0FEC0>, <uiautomator2.Device object at 0x0000017...
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\site-packages\uiautomator2\_input.py", line 103, in _must_broadcast
result = self._broadcast(action, extras)
│ │ │ └ {}
│ │ └ 'ADB_KEYBOARD_HIDE'
│ └ <function InputMethodMixIn._broadcast at 0x0000017566B0FD80>
└ <uiautomator2.Device object at 0x00000175671EDF30>
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\site-packages\uiautomator2\_input.py", line 94, in _broadcast
output = self.shell(args).output
│ │ └ ['am', 'broadcast', '-a', 'ADB_KEYBOARD_HIDE']
│ └ <function _BaseClient.shell at 0x0000017566B46200>
└ <uiautomator2.Device object at 0x00000175671EDF30>
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\site-packages\uiautomator2\base.py", line 114, in shell
raise AdbShellError(e)
└ <class 'uiautomator2.exceptions.AdbShellError'>
uiautomator2.exceptions.AdbShellError: closed
2026-08-14 09:50:47.338 | SUCCESS | __mp_main__:human_like_scroll:253 - xhs_app:172.20.1.44 user_id -> 59c12e4150c4b45e2db6fff1 spider_count -> 11
2026-08-14 09:50:49.349 | SUCCESS | __mp_main__:human_like_scroll:253 - xhs_app:172.20.1.44 user_id -> 59c12e4150c4b45e2db6fff1 spider_count -> 11
2026-08-14 09:50:51.678 | SUCCESS | __mp_main__:human_like_scroll:253 - xhs_app:172.20.1.44 user_id -> 59c12e4150c4b45e2db6fff1 spider_count -> 12
2026-08-14 09:50:53.638 | SUCCESS | __mp_main__:human_like_scroll:253 - xhs_app:172.20.1.44 user_id -> 59c12e4150c4b45e2db6fff1 spider_count -> 12
2026-08-14 09:50:54.363 | SUCCESS | __mp_main__:wait_until_online:732 - 172.20.1.25:5555 ADB 已连续稳定 5 秒(端口 5037)
2026-08-14 09:50:55.310 | SUCCESS | __mp_main__:human_like_scroll:253 - xhs_app:172.20.1.44 user_id -> 59c12e4150c4b45e2db6fff1 spider_count -> 12
2026-08-14 09:50:56.759 | SUCCESS | __mp_main__:human_like_scroll:253 - xhs_app:172.20.1.44 user_id -> 59c12e4150c4b45e2db6fff1 spider_count -> 12
2026-08-14 09:50:58.266 | SUCCESS | __mp_main__:human_like_scroll:253 - xhs_app:172.20.1.44 user_id -> 59c12e4150c4b45e2db6fff1 spider_count -> 13
2026-08-14 09:51:00.723 | SUCCESS | __mp_main__:human_like_scroll:253 - xhs_app:172.20.1.44 user_id -> 59c12e4150c4b45e2db6fff1 spider_count -> 13
2026-08-14 09:51:01.231 | SUCCESS | __mp_main__:check_status:562 - com.xingin.alioth.search.GlobalSearchActivity
2026-08-14 09:51:01.231 | SUCCESS | __mp_main__:worker:918 - 172.20.1.25 当前搜索用户:6846395e000000001d026d76 42275720349
2026-08-14 09:51:02.137 | SUCCESS | __mp_main__:check_status:562 - com.xingin.alioth.search.GlobalSearchActivity
2026-08-14 09:51:02.137 | SUCCESS | __mp_main__:_search_user_id_first:499 - 先使用 user_id 搜索达人: 6846395e000000001d026d76
2026-08-14 09:51:02.675 | SUCCESS | __mp_main__:human_like_scroll:253 - xhs_app:172.20.1.44 user_id -> 59c12e4150c4b45e2db6fff1 spider_count -> 13
2026-08-14 09:51:03.484 | ERROR | __mp_main__:worker:931 - 172.20.1.25 ADB 状态异常(offline),准备重建当前手机会话
Traceback (most recent call last):
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\site-packages\uiautomator2\base.py", line 111, in shell
ret = self._dev.shell2(cmdargs, timeout=timeout)
│ │ │ │ └ 60
│ │ │ └ ['am', 'broadcast', '-a', 'ADB_KEYBOARD_INPUT_TEXT', '--es', 'text', 'Njg0NjM5NWUwMDAwMDAwMDFkMDI2ZDc2']
│ │ └ <function BaseDevice.shell2 at 0x0000017565E01EE0>
│ └ AdbDevice(serial=172.20.1.25:5555)
└ <uiautomator2.Device object at 0x00000175670F31D0>
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\site-packages\adbutils\_device_base.py", line 334, in shell2
result = self._shell_v1(cmdargs, timeout)
│ │ │ └ 60
│ │ └ 'am broadcast -a ADB_KEYBOARD_INPUT_TEXT --es text Njg0NjM5NWUwMDAwMDAwMDFkMDI2ZDc2'
│ └ <function BaseDevice._shell_v1 at 0x0000017565E01F80>
└ AdbDevice(serial=172.20.1.25:5555)
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\site-packages\adbutils\_device_base.py", line 357, in _shell_v1
raise AdbError("shell output invalid", newcmd, output)
│ │ └ b'Broadcasting: Intent { act=ADB_KEYBOARD_INPUT_TEXT flg=0x400000 (has extras) }\n'
│ └ 'am broadcast -a ADB_KEYBOARD_INPUT_TEXT --es text Njg0NjM5NWUwMDAwMDAwMDFkMDI2ZDc2; echo X4EXIT:$?'
└ <class 'adbutils.errors.AdbError'>
adbutils.errors.AdbError: ('shell output invalid', 'am broadcast -a ADB_KEYBOARD_INPUT_TEXT --es text Njg0NjM5NWUwMDAwMDAwMDFkMDI2ZDc2; echo X4EXIT:$?', b'Broadcasting: Intent { act=ADB_KEYBOARD_INPUT_TEXT flg=0x400000 (has extras) }\n')
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\multiprocessing\spawn.py", line 122, in spawn_main
exitcode = _main(fd, parent_sentinel)
│ │ └ 340
│ └ 3
└ <function _main at 0x0000017563AE1080>
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\multiprocessing\spawn.py", line 135, in _main
return self._bootstrap(parent_sentinel)
│ │ └ 340
│ └ <function BaseProcess._bootstrap at 0x00000175637E6E80>
└ <Process name='Process-2' parent=16452 started>
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\multiprocessing\process.py", line 313, in _bootstrap
self.run()
│ └ <function BaseProcess.run at 0x0000017563794CC0>
└ <Process name='Process-2' parent=16452 started>
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\multiprocessing\process.py", line 108, in run
self._target(*self._args, **self._kwargs)
│ │ │ │ │ └ {}
│ │ │ │ └ <Process name='Process-2' parent=16452 started>
│ │ │ └ ('172.20.1.25', 1)
│ │ └ <Process name='Process-2' parent=16452 started>
│ └ <function worker at 0x00000175671FD080>
└ <Process name='Process-2' parent=16452 started>
> File "C:\Users\cuish\auto_xhs\xhs_auto_app_search_user.py", line 919, in worker
auto_operation(d, user_id, red_id, client_ip)
│ │ │ │ └ '172.20.1.25'
│ │ │ └ '42275720349'
│ │ └ '6846395e000000001d026d76'
│ └ <uiautomator2.Device object at 0x00000175670F31D0>
└ <function auto_operation at 0x00000175671FCFE0>
File "C:\Users\cuish\auto_xhs\xhs_auto_app_search_user.py", line 877, in auto_operation
do_search_scroll(d, user_id, red_id, client_ip)
│ │ │ │ └ '172.20.1.25'
│ │ │ └ '42275720349'
│ │ └ '6846395e000000001d026d76'
│ └ <uiautomator2.Device object at 0x00000175670F31D0>
└ <function do_search_scroll at 0x00000175671FC4A0>
File "C:\Users\cuish\auto_xhs\xhs_auto_app_search_user.py", line 520, in do_search_scroll
if _search_user_id_first(d, user_id, red_id, client_ip):
│ │ │ │ └ '172.20.1.25'
│ │ │ └ '42275720349'
│ │ └ '6846395e000000001d026d76'
│ └ <uiautomator2.Device object at 0x00000175670F31D0>
└ <function _search_user_id_first at 0x00000175671FC400>
File "C:\Users\cuish\auto_xhs\xhs_auto_app_search_user.py", line 500, in _search_user_id_first
if not _input_and_submit_search(d, user_id):
│ │ └ '6846395e000000001d026d76'
│ └ <uiautomator2.Device object at 0x00000175670F31D0>
└ <function _input_and_submit_search at 0x00000175671FC180>
File "C:\Users\cuish\auto_xhs\xhs_auto_app_search_user.py", line 416, in _input_and_submit_search
d.send_keys(keyword)
│ │ └ '6846395e000000001d026d76'
│ └ <function Device.send_keys at 0x0000017566B53100>
└ <uiautomator2.Device object at 0x00000175670F31D0>
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\site-packages\uiautomator2\__init__.py", line 883, in send_keys
InputMethodMixIn.send_keys(self, text)
│ │ │ └ '6846395e000000001d026d76'
│ │ └ <uiautomator2.Device object at 0x00000175670F31D0>
│ └ <function InputMethodMixIn.send_keys at 0x0000017566B0FF60>
└ <class 'uiautomator2._input.InputMethodMixIn'>
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\site-packages\uiautomator2\_input.py", line 113, in send_keys
self._must_broadcast(cmd, {"text": base64text})
│ │ │ └ 'Njg0NjM5NWUwMDAwMDAwMDFkMDI2ZDc2'
│ │ └ 'ADB_KEYBOARD_INPUT_TEXT'
│ └ <function InputMethodMixIn._must_broadcast at 0x0000017566B140E0>
└ <uiautomator2.Device object at 0x00000175670F31D0>
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\site-packages\decorator.py", line 235, in fun
return caller(func, *(extras + args), **kw)
│ │ │ │ └ {}
│ │ │ └ (<uiautomator2.Device object at 0x00000175670F31D0>, 'ADB_KEYBOARD_INPUT_TEXT', {'text': 'Njg0NjM5NWUwMDAwMDAwMDFkMDI2ZDc2'})
│ │ └ ()
│ └ <function InputMethodMixIn._must_broadcast at 0x0000017566B0FEC0>
└ <function retry.<locals>.retry_decorator at 0x0000017566B0FE20>
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\site-packages\retry\api.py", line 90, in retry_decorator
return __retry_internal(partial(f, *args, **kwargs), exceptions, tries, delay, max_delay, backoff, jitter,
│ │ │ │ │ │ │ │ │ │ └ 0.5
│ │ │ │ │ │ │ │ │ └ 1
│ │ │ │ │ │ │ │ └ None
│ │ │ │ │ │ │ └ 1
│ │ │ │ │ │ └ 3
│ │ │ │ │ └ <class 'uiautomator2.exceptions.AdbBroadcastError'>
│ │ │ │ └ {}
│ │ │ └ (<uiautomator2.Device object at 0x00000175670F31D0>, 'ADB_KEYBOARD_INPUT_TEXT', {'text': 'Njg0NjM5NWUwMDAwMDAwMDFkMDI2ZDc2'})
│ │ └ <function InputMethodMixIn._must_broadcast at 0x0000017566B0FEC0>
│ └ <class 'functools.partial'>
└ <function __retry_internal at 0x0000017566A18540>
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\site-packages\retry\api.py", line 35, in __retry_internal
return f()
└ functools.partial(<function InputMethodMixIn._must_broadcast at 0x0000017566B0FEC0>, <uiautomator2.Device object at 0x0000017...
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\site-packages\uiautomator2\_input.py", line 103, in _must_broadcast
result = self._broadcast(action, extras)
│ │ │ └ {'text': 'Njg0NjM5NWUwMDAwMDAwMDFkMDI2ZDc2'}
│ │ └ 'ADB_KEYBOARD_INPUT_TEXT'
│ └ <function InputMethodMixIn._broadcast at 0x0000017566B0FD80>
└ <uiautomator2.Device object at 0x00000175670F31D0>
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\site-packages\uiautomator2\_input.py", line 94, in _broadcast
output = self.shell(args).output
│ │ └ ['am', 'broadcast', '-a', 'ADB_KEYBOARD_INPUT_TEXT', '--es', 'text', 'Njg0NjM5NWUwMDAwMDAwMDFkMDI2ZDc2']
│ └ <function _BaseClient.shell at 0x0000017566B46200>
└ <uiautomator2.Device object at 0x00000175670F31D0>
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\site-packages\uiautomator2\base.py", line 114, in shell
raise AdbShellError(e)
└ <class 'uiautomator2.exceptions.AdbShellError'>
uiautomator2.exceptions.AdbShellError: ('shell output invalid', 'am broadcast -a ADB_KEYBOARD_INPUT_TEXT --es text Njg0NjM5NWUwMDAwMDAwMDFkMDI2ZDc2; echo X4EXIT:$?', b'Broadcasting: Intent { act=ADB_KEYBOARD_INPUT_TEXT flg=0x400000 (has extras) }\n')
2026-08-14 09:51:04.475 | SUCCESS | __mp_main__:human_like_scroll:253 - xhs_app:172.20.1.44 user_id -> 59c12e4150c4b45e2db6fff1 spider_count -> 13
2026-08-14 09:51:05.393 | SUCCESS | __mp_main__:human_like_scroll:253 - xhs_app:172.20.1.44 user_id -> 59c12e4150c4b45e2db6fff1 spider_count -> 13
2026-08-14 09:51:06.964 | SUCCESS | __mp_main__:human_like_scroll:253 - xhs_app:172.20.1.44 user_id -> 59c12e4150c4b45e2db6fff1 spider_count -> 14
2026-08-14 09:51:09.163 | SUCCESS | __mp_main__:human_like_scroll:253 - xhs_app:172.20.1.44 user_id -> 59c12e4150c4b45e2db6fff1 spider_count -> 14
2026-08-14 09:51:11.635 | SUCCESS | __mp_main__:human_like_scroll:253 - xhs_app:172.20.1.44 user_id -> 59c12e4150c4b45e2db6fff1 spider_count -> 14
2026-08-14 09:51:12.586 | SUCCESS | __mp_main__:wait_until_online:732 - 172.20.1.25:5555 ADB 已连续稳定 5 秒(端口 5037)
2026-08-14 09:51:15.520 | SUCCESS | __mp_main__:human_like_scroll:253 - xhs_app:172.20.1.44 user_id -> 59c12e4150c4b45e2db6fff1 spider_count -> 15
2026-08-14 09:51:15.520 | SUCCESS | __mp_main__:human_like_scroll:262 - 59c12e4150c4b45e2db6fff1 当前已拦截15次 退出滑动 收录设置为1
2026-08-14 09:51:15.584 | SUCCESS | __mp_main__:worker:918 - 172.20.1.44 当前搜索用户:65447b9c000000000301e7f9 a47483801
2026-08-14 09:51:16.768 | SUCCESS | __mp_main__:check_status:562 - com.xingin.matrix.v2.profile.newpage.NewOtherUserActivity
2026-08-14 09:51:16.768 | SUCCESS | __mp_main__:check_status:574 - 正在用户详情页面 回退
2026-08-14 09:51:19.438 | SUCCESS | __mp_main__:check_status:562 - com.xingin.alioth.search.GlobalSearchActivity
2026-08-14 09:51:19.439 | SUCCESS | __mp_main__:worker:918 - 172.20.1.25 当前搜索用户:6846395e000000001d026d76 42275720349
2026-08-14 09:51:20.424 | SUCCESS | __mp_main__:check_status:562 - com.xingin.alioth.search.GlobalSearchActivity
2026-08-14 09:51:20.424 | SUCCESS | __mp_main__:_search_user_id_first:499 - 先使用 user_id 搜索达人: 6846395e000000001d026d76
2026-08-14 09:51:21.036 | SUCCESS | __mp_main__:_open_search_input:385 - 清空上次搜索内容
2026-08-14 09:51:21.094 | SUCCESS | __mp_main__:check_status:562 - com.xingin.alioth.search.GlobalSearchActivity
2026-08-14 09:51:21.094 | SUCCESS | __mp_main__:_search_user_id_first:499 - 先使用 user_id 搜索达人: 65447b9c000000000301e7f9
2026-08-14 09:51:21.788 | SUCCESS | __mp_main__:_open_search_input:385 - 清空上次搜索内容
2026-08-14 09:51:24.414 | ERROR | __mp_main__:worker:931 - 172.20.1.25 ADB 状态异常(offline),准备重建当前手机会话
Traceback (most recent call last):
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\site-packages\uiautomator2\core.py", line 97, in connect
self.sock = self.__device.create_connection(adbutils.Network.TCP, self.__port)
│ │ │ │ │ │ └ <uiautomator2.core.AdbHTTPConnection object at 0x00000175671720B0>
│ │ │ │ │ └ <Network.TCP: 'tcp'>
│ │ │ │ └ <enum 'Network'>
│ │ │ └ <module 'adbutils' from 'C:\\Users\\cuish\\anaconda3\\envs\\xhs\\Lib\\site-packages\\adbutils\\__init__.py'>
│ │ └ <uiautomator2.core.AdbHTTPConnection object at 0x00000175671720B0>
│ └ None
└ <uiautomator2.core.AdbHTTPConnection object at 0x00000175671720B0>
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\site-packages\adbutils\_device_base.py", line 610, in create_connection
return _connect(c)
│ └ <adbutils._adb.AdbConnection object at 0x000001756727B530>
└ <function BaseDevice.create_connection.<locals>._connect at 0x0000017567227C40>
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\site-packages\adbutils\_device_base.py", line 591, in _connect
c.check_okay()
│ └ <function AdbConnection.check_okay at 0x0000017565D6A3E0>
└ <adbutils._adb.AdbConnection object at 0x000001756727B530>
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\site-packages\adbutils\_adb.py", line 192, in check_okay
raise AdbError(self.read_string_block())
│ │ └ <function AdbConnection.read_string_block at 0x0000017565D6A2A0>
│ └ <adbutils._adb.AdbConnection object at 0x000001756727B530>
└ <class 'adbutils.errors.AdbError'>
adbutils.errors.AdbError: closed
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\site-packages\uiautomator2\core.py", line 311, in jsonrpc_call
return _jsonrpc_call(self._dev, self._device_server_port, method, params, timeout, self._debug)
│ │ │ │ │ │ │ │ │ └ False
│ │ │ │ │ │ │ │ └ <uiautomator2.Device object at 0x0000017567127240>
│ │ │ │ │ │ │ └ 300
│ │ │ │ │ │ └ ({'mask': 1, 'childOrSibling': [], 'childOrSiblingSelector': [], 'text': '搜索'},)
│ │ │ │ │ └ 'objInfo'
│ │ │ │ └ 9008
│ │ │ └ <uiautomator2.Device object at 0x0000017567127240>
│ │ └ AdbDevice(serial=172.20.1.25:5555)
│ └ <uiautomator2.Device object at 0x0000017567127240>
└ <function _jsonrpc_call at 0x0000017566B174C0>
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\site-packages\uiautomator2\core.py", line 173, in _jsonrpc_call
r = _http_request(dev, device_port, "POST", "/jsonrpc/0", payload, timeout=timeout, print_request=print_request)
│ │ │ │ │ └ False
│ │ │ │ └ 300
│ │ │ └ {'jsonrpc': '2.0', 'id': 1, 'method': 'objInfo', 'params': ({'mask': 1, 'childOrSibling': [], 'childOrSiblingSelector': [], '...
│ │ └ 9008
│ └ AdbDevice(serial=172.20.1.25:5555)
└ <function _http_request at 0x0000017566B17380>
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\site-packages\uiautomator2\core.py", line 139, in _http_request
conn.request(method, path, json.dumps(data), headers=headers)
│ │ │ │ │ │ │ └ {'User-Agent': 'uiautomator2', 'Accept-Encoding': '', 'Content-Type': 'application/json'}
│ │ │ │ │ │ └ {'jsonrpc': '2.0', 'id': 1, 'method': 'objInfo', 'params': ({'mask': 1, 'childOrSibling': [], 'childOrSiblingSelector': [], '...
│ │ │ │ │ └ <function dumps at 0x0000017565C50C20>
│ │ │ │ └ <module 'json' from 'C:\\Users\\cuish\\anaconda3\\envs\\xhs\\Lib\\json\\__init__.py'>
│ │ │ └ '/jsonrpc/0'
│ │ └ 'POST'
│ └ <function HTTPConnection.request at 0x0000017565E3E5C0>
└ <uiautomator2.core.AdbHTTPConnection object at 0x00000175671720B0>
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\http\client.py", line 1358, in request
self._send_request(method, url, body, headers, encode_chunked)
│ │ │ │ │ │ └ False
│ │ │ │ │ └ {'User-Agent': 'uiautomator2', 'Accept-Encoding': '', 'Content-Type': 'application/json'}
│ │ │ │ └ '{"jsonrpc": "2.0", "id": 1, "method": "objInfo", "params": [{"mask": 1, "childOrSibling": [], "childOrSiblingSelector": [], ...
│ │ │ └ '/jsonrpc/0'
│ │ └ 'POST'
│ └ <function HTTPConnection._send_request at 0x0000017565E3E660>
└ <uiautomator2.core.AdbHTTPConnection object at 0x00000175671720B0>
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\http\client.py", line 1404, in _send_request
self.endheaders(body, encode_chunked=encode_chunked)
│ │ │ └ False
│ │ └ b'{"jsonrpc": "2.0", "id": 1, "method": "objInfo", "params": [{"mask": 1, "childOrSibling": [], "childOrSiblingSelector": [],...
│ └ <function HTTPConnection.endheaders at 0x0000017565E3E520>
└ <uiautomator2.core.AdbHTTPConnection object at 0x00000175671720B0>
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\http\client.py", line 1353, in endheaders
self._send_output(message_body, encode_chunked=encode_chunked)
│ │ │ └ False
│ │ └ b'{"jsonrpc": "2.0", "id": 1, "method": "objInfo", "params": [{"mask": 1, "childOrSibling": [], "childOrSiblingSelector": [],...
│ └ <function HTTPConnection._send_output at 0x0000017565E3E0C0>
└ <uiautomator2.core.AdbHTTPConnection object at 0x00000175671720B0>
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\http\client.py", line 1113, in _send_output
self.send(msg)
│ │ └ b'POST /jsonrpc/0 HTTP/1.1\r\nHost: localhost:9008\r\nContent-Length: 149\r\nUser-Agent: uiautomator2\r\nAccept-Encoding: \r\...
│ └ <function HTTPConnection.send at 0x0000017565E3DEE0>
└ <uiautomator2.core.AdbHTTPConnection object at 0x00000175671720B0>
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\http\client.py", line 1057, in send
self.connect()
│ └ <function AdbHTTPConnection.connect at 0x0000017566B171A0>
└ <uiautomator2.core.AdbHTTPConnection object at 0x00000175671720B0>
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\site-packages\uiautomator2\core.py", line 99, in connect
raise HTTPError(f"Unable to connect to uiautomator2 server: {e}") from e
└ <class 'uiautomator2.exceptions.HTTPError'>
uiautomator2.exceptions.HTTPError: Unable to connect to uiautomator2 server: closed
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\multiprocessing\spawn.py", line 122, in spawn_main
exitcode = _main(fd, parent_sentinel)
│ │ └ 340
│ └ 3
└ <function _main at 0x0000017563AE1080>
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\multiprocessing\spawn.py", line 135, in _main
return self._bootstrap(parent_sentinel)
│ │ └ 340
│ └ <function BaseProcess._bootstrap at 0x00000175637E6E80>
└ <Process name='Process-2' parent=16452 started>
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\multiprocessing\process.py", line 313, in _bootstrap
self.run()
│ └ <function BaseProcess.run at 0x0000017563794CC0>
└ <Process name='Process-2' parent=16452 started>
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\multiprocessing\process.py", line 108, in run
self._target(*self._args, **self._kwargs)
│ │ │ │ │ └ {}
│ │ │ │ └ <Process name='Process-2' parent=16452 started>
│ │ │ └ ('172.20.1.25', 1)
│ │ └ <Process name='Process-2' parent=16452 started>
│ └ <function worker at 0x00000175671FD080>
└ <Process name='Process-2' parent=16452 started>
> File "C:\Users\cuish\auto_xhs\xhs_auto_app_search_user.py", line 919, in worker
auto_operation(d, user_id, red_id, client_ip)
│ │ │ │ └ '172.20.1.25'
│ │ │ └ '42275720349'
│ │ └ '6846395e000000001d026d76'
│ └ <uiautomator2.Device object at 0x0000017567127240>
└ <function auto_operation at 0x00000175671FCFE0>
File "C:\Users\cuish\auto_xhs\xhs_auto_app_search_user.py", line 877, in auto_operation
do_search_scroll(d, user_id, red_id, client_ip)
│ │ │ │ └ '172.20.1.25'
│ │ │ └ '42275720349'
│ │ └ '6846395e000000001d026d76'
│ └ <uiautomator2.Device object at 0x0000017567127240>
└ <function do_search_scroll at 0x00000175671FC4A0>
File "C:\Users\cuish\auto_xhs\xhs_auto_app_search_user.py", line 520, in do_search_scroll
if _search_user_id_first(d, user_id, red_id, client_ip):
│ │ │ │ └ '172.20.1.25'
│ │ │ └ '42275720349'
│ │ └ '6846395e000000001d026d76'
│ └ <uiautomator2.Device object at 0x0000017567127240>
└ <function _search_user_id_first at 0x00000175671FC400>
File "C:\Users\cuish\auto_xhs\xhs_auto_app_search_user.py", line 500, in _search_user_id_first
if not _input_and_submit_search(d, user_id):
│ │ └ '6846395e000000001d026d76'
│ └ <uiautomator2.Device object at 0x0000017567127240>
└ <function _input_and_submit_search at 0x00000175671FC180>
File "C:\Users\cuish\auto_xhs\xhs_auto_app_search_user.py", line 419, in _input_and_submit_search
d(text="搜索").click()
└ <uiautomator2.Device object at 0x0000017567127240>
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\site-packages\uiautomator2\_selector.py", line 150, in click
x, y = self.center(offset=offset)
│ │ └ None
│ └ <function UiObject.center at 0x0000017566B15300>
└ <uiautomator2._selector.UiObject object at 0x000001756727B5F0>
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\site-packages\uiautomator2\_selector.py", line 171, in center
lx, ly, rx, ry = self.bounds()
│ └ <function UiObject.bounds at 0x0000017566B15260>
└ <uiautomator2._selector.UiObject object at 0x000001756727B5F0>
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\site-packages\uiautomator2\_selector.py", line 158, in bounds
info = self.info
│ └ <property object at 0x0000017566AD1580>
└ <uiautomator2._selector.UiObject object at 0x000001756727B5F0>
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\site-packages\uiautomator2\_selector.py", line 128, in info
return self.jsonrpc.objInfo(self.selector)
│ │ │ └ {'mask': 1, 'childOrSibling': [], 'childOrSiblingSelector': [], 'text': '搜索'}
│ │ └ <uiautomator2._selector.UiObject object at 0x000001756727B5F0>
│ └ <uiautomator2.base._BaseClient.jsonrpc.<locals>.JSONRpcWrapper object at 0x000001756719AE40>
└ <uiautomator2._selector.UiObject object at 0x000001756727B5F0>
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\site-packages\uiautomator2\base.py", line 158, in __call__
return self.server.jsonrpc_call(self.method, params, http_timeout)
│ │ │ │ │ │ └ 300
│ │ │ │ │ └ ({'mask': 1, 'childOrSibling': [], 'childOrSiblingSelector': [], 'text': '搜索'},)
│ │ │ │ └ 'objInfo'
│ │ │ └ <uiautomator2.base._BaseClient.jsonrpc.<locals>.JSONRpcWrapper object at 0x000001756719AE40>
│ │ └ <function BasicUiautomatorServer.jsonrpc_call at 0x0000017566B17C40>
│ └ <uiautomator2.Device object at 0x0000017567127240>
└ <uiautomator2.base._BaseClient.jsonrpc.<locals>.JSONRpcWrapper object at 0x000001756719AE40>
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\site-packages\uiautomator2\core.py", line 315, in jsonrpc_call
self.start_uiautomator()
│ └ <function BasicUiautomatorServer.start_uiautomator at 0x0000017566B177E0>
└ <uiautomator2.Device object at 0x0000017567127240>
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\site-packages\uiautomator2\core.py", line 231, in start_uiautomator
self._setup_jar()
│ └ <function BasicUiautomatorServer._setup_jar at 0x0000017566B17880>
└ <uiautomator2.Device object at 0x0000017567127240>
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\site-packages\uiautomator2\core.py", line 242, in _setup_jar
if self._check_device_file_hash(jar_path, target_path):
│ │ │ └ '/data/local/tmp/u2.jar'
│ │ └ WindowsPath('C:/Users/cuish/anaconda3/envs/xhs/Lib/site-packages/uiautomator2/assets/u2.jar')
│ └ <function BasicUiautomatorServer._check_device_file_hash at 0x0000017566B17920>
└ <uiautomator2.Device object at 0x0000017567127240>
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\site-packages\uiautomator2\core.py", line 255, in _check_device_file_hash
output = self._dev.shell(["toybox", "md5sum", remote_file])
│ │ │ └ '/data/local/tmp/u2.jar'
│ │ └ <function BaseDevice.shell at 0x0000017565E01BC0>
│ └ AdbDevice(serial=172.20.1.25:5555)
└ <uiautomator2.Device object at 0x0000017567127240>
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\site-packages\adbutils\_device_base.py", line 252, in shell
c = self.open_shell(cmdargs)
│ │ └ 'toybox md5sum /data/local/tmp/u2.jar'
│ └ <function BaseDevice.open_shell at 0x0000017565E01800>
└ AdbDevice(serial=172.20.1.25:5555)
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\site-packages\adbutils\_device_base.py", line 175, in open_shell
c = self.open_transport()
│ └ <function BaseDevice.open_transport at 0x0000017565E011C0>
└ AdbDevice(serial=172.20.1.25:5555)
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\site-packages\adbutils\_device_base.py", line 92, in open_transport
c.check_okay()
│ └ <function AdbConnection.check_okay at 0x0000017565D6A3E0>
└ <adbutils._adb.AdbConnection object at 0x000001756722A7B0>
File "C:\Users\cuish\anaconda3\envs\xhs\Lib\site-packages\adbutils\_adb.py", line 192, in check_okay
raise AdbError(self.read_string_block())
│ │ └ <function AdbConnection.read_string_block at 0x0000017565D6A2A0>
│ └ <adbutils._adb.AdbConnection object at 0x000001756722A7B0>
└ <class 'adbutils.errors.AdbError'>
adbutils.errors.AdbError: device offline
@echo off
call C:\Users\cuish\anaconda3\Scripts\activate.bat xhs
cd /d C:\Users\cuish\auto_xhs
python -u xhs_auto_app_search_user.py > C:\Users\cuish\auto_xhs\debug_logs\cmd_run_20260814.log 2>&1
@echo off
adb -P 5037 track-devices > C:\Users\cuish\auto_xhs\debug_logs\adb_track_20260814.log 2>&1
import math
import multiprocessing
import random
import subprocess
import time
import requests
import uiautomator2 as u2
from loguru import logger
from redis import Redis
common_redis4 = Redis(host='172.16.0.24', password="aiyingli@@123", port=6379, db=4, decode_responses=True)
class DeviceManager:
"""设备管理"""
@staticmethod
def start_app(d):
d.app_start("com.ss.android.ugc.aweme")
@staticmethod
def close_app(d):
d.app_stop("com.ss.android.ugc.aweme")
def clear_package(device_ip):
cmd = f"adb -s {device_ip} shell pm clear com.ss.android.ugc.aweme"
subprocess.run(cmd, shell=True)
def connect_phone(device_ip):
cmd = f"adb connect {device_ip}"
subprocess.run(cmd, shell=True)
def dump_page(d, name):
"""保存页面 XML,用于调试"""
xml = d.dump_hierarchy()
if not name:
name = "./test"
else:
name = "./" + name
with open(f'{name}.xml', 'w', encoding='utf-8') as f:
f.write(xml)
def page_text_click(d, text):
start_time = int(time.time())
while int(time.time()) - start_time <= 20:
if d(text=text).exists:
# logger.success(f"成功找到{text} 开始进行点击操作")
time.sleep(2)
d(text=text).click()
break
else:
time.sleep(2)
continue
def page_desc_click(d, text):
start_time = int(time.time())
while int(time.time()) - start_time <= 20:
if d(description=text).exists:
# logger.success(f"成功找到{text} 开始进行点击操作")
time.sleep(2)
d(description=text).click()
break
else:
logger.error(f"未找到{text} 无法进行点击操作 等待两秒后再次查看")
time.sleep(2)
continue
def input_text(d, text):
d(resourceId="com.ss.android.ugc.aweme:id/et_search_kw").set_text(text)
def auto_slide(d, value):
if d(resourceId="captcha-verify_img_slide").exists:
bounds = d(resourceId="captcha-verify_img_slide").bounds()
left, top, right, bottom = bounds
# 滑块的宽度
slide_width = right - left
# 滑动起点(从滑块中心)
start_x = (left + right) // 2
start_y = (top + bottom) // 2
# 滑动终点:缺口位置 (value) + 滑块左边缘相对于中心的偏移量
end_x = start_x + value + (slide_width // 2) - 2
# end_x = start_x + value
end_y = start_y
d.swipe(start_x, start_y, end_x, end_y, duration=0.3)
print("滑动操作完成")
elif d(className="android.view.View", clickable=True, index=1).exists:
elements = d(className="android.view.View", clickable=True, index=1)
bounds = elements[0].bounds()
left, top, right, bottom = bounds
left = 144
start_x, start_y = (left + right) // 2, (top + bottom) // 2
end_x, end_y = start_x + value, (top + bottom) // 2
d.swipe(start_x, start_y, end_x, end_y, duration=0.3)
else:
print("未找到滑动按钮")
def human_like_scroll(d):
d.swipe(
random.randint(190, 770),
random.randint(1000, 1200),
random.randint(190, 770),
random.randint(300, 450),
0.05
)
def search_keyword(d):
page_desc_click(d, "搜索")
for i in range(3):
keyword = common_redis4.srandmember("search_keyword")
logger.info(f"正在输入词:{keyword}")
for char in keyword[:3]:
d.send_keys(char)
time.sleep(random.uniform(0.1, 0.3))
time.sleep(1)
items = d(resourceId="com.ss.android.ugc.aweme:id/1-3")
# for i, item in enumerate(items):
# print(i, item.get_text())
if not items.exists:
print("❌ 未找到候选词")
# dump_page(d, "xx3")
page_text_click(d, "搜索")
else:
count = len(items)
logger.success(f"共找到 {count} 个推荐词")
# 随机选择一个
idx = random.randint(3, count - 1)
item = items[idx]
text = item.get_text()
print(f"🎯 随机选中: {text}")
if text == keyword[:3]:
page_text_click(d, "搜索")
else:
d(text=text).click()
time.sleep(2)
if d(text="搜索结果为空").exists:
time.sleep(2)
if d(resourceId="com.ss.android.ugc.aweme:id/btn_clear").exists:
d(resourceId="com.ss.android.ugc.aweme:id/btn_clear").click()
continue
else:
return True
else:
return False
def worker(device_ip):
common_redis4.hdel("dy_app_auto_address", device_ip)
connect_phone(device_ip)
# common_redis4.hset("dy_app_auto_status",device_ip,"connect")
d = u2.Device(device_ip)
time.sleep(2)
while 1:
try:
clear_package(device_ip)
DeviceManager.start_app(d)
common_redis4.hset("dy_app_auto_status", device_ip, "start")
time.sleep(5)
common_redis4.hset("dy_app_auto_status", device_ip, "auto")
page_text_click(d, "同意")
time.sleep(2)
# 滑动两次 释放
human_like_scroll(d)
time.sleep(1)
human_like_scroll(d)
time.sleep(2)
if d(text="拒绝").exists:
d(text="拒绝").click()
# time.sleep(1)
# for i in range(3):
# if d(text="拒绝").exists:
# d(text="拒绝").click()
# human_like_scroll(d)
# time.sleep(1)
time.sleep(2)
if not search_keyword(d):
logger.error(f"{device_ip} 获取搜索结果失败")
continue
time.sleep(10)
image_load_time = int(time.time())
while int(time.time()) - image_load_time <= 12:
logger.info(f"当前已耗时:{int(time.time()) - image_load_time}")
# 判断图片是否加载完成
if d(text="网络故障,请稍后重试[5105]").exists:
logger.error(f"{device_ip} 当前网络故障 刷新图片")
d(text="刷新").click()
image_load_time = int(time.time())
time.sleep(5)
elif d(text="图片加载失败,请刷新重试[5201]").exists:
logger.error(f"{device_ip} 当前网络故障 刷新图片")
d(text="刷新").click()
image_load_time = int(time.time())
time.sleep(5)
time.sleep(1)
logger.info("图片加载完成 开始进行验证码识别阶段")
while 1:
# 循环读取redis状态 检测是否过完滑块
status = common_redis4.hget("dy_app_auto_status", device_ip)
if status != "auto":
if status == "slide" or status == "whirl":
for i in range(3):
logger.warning(f"当前验证码为:{status} 等待获取坐标进行操作")
address = common_redis4.hget("dy_app_auto_address", device_ip)
if address:
logger.info(f"{device_ip} 已经获取坐标 : {address} 开始进行操作")
auto_slide(d, int(address))
common_redis4.hset("dy_app_auto_status", device_ip, 'operation_ok')
common_redis4.hdel("dy_app_auto_address", device_ip)
flag = True
load_time = int(time.time())
while int(time.time()) - load_time <= 20:
status = common_redis4.hget("dy_app_auto_status", device_ip)
logger.success(f"当前状态 {status}")
if status == "verify_success":
flag = True
break
else:
if status == "verify_error":
if d(text="刷新").exists:
d(text="刷新").click()
time.sleep(5)
flag = False
break
elif status == "verify_fail":
time.sleep(5)
flag = False
break
elif status != "operation_ok":
flag = False
break
else:
logger.warning(f"当前状态未发生变化,还未加载完成 {status}")
flag = False
time.sleep(2)
continue
if flag:
break
clear_package(device_ip)
common_redis4.hdel("dy_app_auto_address", device_ip)
common_redis4.hset("dy_app_auto_status", device_ip, "over")
break
else:
logger.warning(f"{device_ip} 当前auto状态异常 重新清理app状态")
clear_package(device_ip)
common_redis4.hdel("dy_app_auto_address", device_ip)
common_redis4.hset("dy_app_auto_status", device_ip, "over")
break
except Exception as e:
logger.error(e)
def worker_test(device_ip):
d = u2.Device(device_ip)
dump_page(d, "xx2")
time.sleep(2)
search_clientip = [
# "172.200.2.210"
# "172.200.2.74",
"172.200.2.118",
"172.200.2.132",
# "172.200.2.83",
"172.200.2.75",
"172.200.2.126",
"172.200.2.81",
]
# https://rmc.bytedance.com/verifycenter/captcha?verify_host=https%3A%2F%2Fverify.zijieapi.com%2F&aid=1128&lang=zh&app_name=aweme&locale=zh_CN&ch=48148318a&channel=48148318a&app_key&iid=1831161685350328&vc=31.8.0&app_verison=31.8.0&did=1831161685346232&region=cn&use_native_report=1&use_jsb_request=1&verify_cancellable=0&orientation=2&resolution=1080*2029&sdk_version=3.7.3.cn&os_version=28&device_brand=Xiaomi&device_model=MI+8&os_name=android&version_code=310801&version_name=31.8.0&device_type=MI+8&device_platform=android&os_type=0&use_dialog_size_v2=1&verify_data=%7B%22code%22%3A%2210000%22%2C%22from%22%3A%22shark_admin%22%2C%22type%22%3A%22verify%22%2C%22version%22%3A%22%22%2C%22region%22%3A%22cn%22%2C%22subtype%22%3A%22slide%22%2C%22ui_type%22%3A%22%22%2C%22detail%22%3A%22qzIwcrGJzEozi5M8jqskWTi1yh7ODh9lB18UMPXQs*aIjZ0lgxyeBNFOqtwanE2fZTLkGD7WTNlkQVeO7o3rVuxI-8sCD*dvrVD35uZ0H0PnKnm*Q4ZsDdJYWlqzImtvini9NDT4ZNLcM*8SmPJOa6a9oRaBMgwNg-kwWJ3lEEbFGXuyEI9IsidEJLZD3HK9dCUlf9OTd58gjUCcq6CAafUvpwOYQ2J9s19d8TVJ2ZLoFHpXRqPXV2VfGmIo4EAFwszU*AtCYWRRtzjOUsqhP-r6xZlLXFtTqxc8-vnNQs4oALB2KntrH9tBpkq7S5FBUrAcXcfPldqdJcdWKxhIkVhJzCKH88ljJ4QKx6ML3iINDBsIOA..%22%2C%22verify_event%22%3A%22%22%2C%22fp%22%3A%22%22%2C%22server_sdk_env%22%3A%22%7B%5C%22idc%5C%22%3A%5C%22lq%5C%22%2C%5C%22region%5C%22%3A%5C%22CN%5C%22%2C%5C%22server_type%5C%22%3A%5C%22business%5C%22%7D%22%2C%22log_id%22%3A%22202510101815025601AE9D201BF5DC0EF1%22%2C%22is_assist_mobile%22%3Afalse%2C%22is_complex_sms%22%3Afalse%2C%22identity_action%22%3A%22%22%2C%22identity_scene%22%3A%22%22%7D
def main( ):
phone_num = len(search_clientip)
processes = []
for idx, ip in enumerate(search_clientip):
p = multiprocessing.Process(target=worker, args=(ip,))
# p = multiprocessing.Process(target=worker_test, args=(ip,))
p.start()
processes.append(p)
for p in processes:
p.join()
if __name__ == '__main__':
main()
import base64
import datetime
import json
import time
import mitmproxy.http
from loguru import logger
from urllib.parse import urlparse
from redis import Redis
import requests
import urllib.parse
from urllib.parse import parse_qs, quote_plus
from hashlib import md5
def extract_params_from_url(url):
"""从URL中提取参数"""
# 解析URL
parsed_url = urllib.parse.urlparse(url)
# 解析查询参数
params = parse_qs(parsed_url.query)
# 提取需要的参数(取第一个值,因为parse_qs返回列表)
device_id = params.get('device_id', [''])[0]
iid = params.get('iid', [''])[0]
return device_id, iid
def get_image_data(img_url):
for i in range(3):
try:
r = requests.get(img_url, headers={'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/139.0.0.0 Safari/537.36'})
return base64.b64encode(r.content)
except Exception as e:
print(e)
continue
def get_slide_addr(image_bytes):
try:
logger.info("开始请求滑块坐标")
res = requests.post("http://127.0.0.1:35846/detect", data=image_bytes).json()
return res
except Exception as e:
logger.error(e)
return False
def verify(type, out_image, inner_image):
url = "http://api.jfbym.com/api/YmServer/customApi"
if type == "90015":
data = {
## 关于参数,一般来说有3个;不同类型id可能有不同的参数个数和参数名,找客服获取
"token": "gHhbPwEYjRnAZ1pA8epncxuiz02t2nKsWtPrNKUiBmA",
"type": type,
"out_ring_image": out_image,
"inner_circle_image": inner_image,
}
elif type == "20111":
data = {
## 关于参数,一般来说有3个;不同类型id可能有不同的参数个数和参数名,找客服获取
"token": "gHhbPwEYjRnAZ1pA8epncxuiz02t2nKsWtPrNKUiBmA",
"type": type,
"background_image": out_image,
"slide_image": inner_image,
}
_headers = {
"Content-Type": "application/json"
}
response = requests.request("POST", url, headers=_headers, json=data)
return response.json()
def xxx(timestamp):
dt = datetime.datetime.fromtimestamp(timestamp)
# 格式化为年月日
return dt.strftime("%Y%m%d")
def convert_headers_to_java_format(headers_dict):
header_list = []
for key, value in headers_dict.items():
header_list.append(key)
header_list.append(value)
return ",".join(header_list)
def search_keyword(device_id, iid):
apiurl = "http://172.16.18.10:9999/api/dy319/sixgod/encrypt"
url = "https://search3-search-lf.amemv.com/aweme/v2/search/general/single/?iid=" + iid + "&device_id=" + device_id + "&ac=wifi&channel=vivo_1128_64&aid=1128&app_name=aweme&version_code=310800&version_name=31.8.0&device_platform=android&os=android&ssmix=a&device_type=MI+8&device_brand=Xiaomi&language=zh&os_api=28&os_version=9&manifest_version_code=310801&resolution=1080*2029&dpi=440&update_version_code=31809900&_rticket=1759210484223&package=com.ss.android.ugc.aweme&first_launch_timestamp=1759209870&last_deeplink_update_version_code=0&cpu_support64=true&host_abi=arm64-v8a&is_guest_mode=0&app_type=normal&minor_status=0&appTheme=light&is_preinstall=0&need_personal_recommend=1&is_android_pad=0&is_android_fold=0"
payload = "filter_selected=%7B%22sort_type%22%3A%220%22%2C%22publish_time%22%3A%220%22%2C%22filter_duration%22%3A%22%22%7D&enter_from=homepage_hot&init_search_source=search_history&is_mute_status=0&extra_server_client_params=%7B%22last_strong_style_card_idx%22%3A0%7D&is_accessibility=0&&from_author_id=94675462500&query_correct_type=1&video_cover_shrink=&is_coin=0&large_font_mode=0&keyword=" + quote_plus("月子餐做法") + "&client_server_extra=&start_session=1&user_avatar_shrink_double=&effect_sdk_version=17.6.0&is_adapt_elder=0&init_search_id=202509261113415E4D75EF3137A25D6A70&search_scene=douyin_search&from_author_id=3793757811250195&count=10&double_column_mode_scene=&need_filter_settings=0&enable_history=1&search_source=search_history&video_cover_shrink_double=&hot_search=0&address_book_access=2&goods_info_version=1&simplify_mix_card_data=1&load_more_ad_info=%7B%22interactive_informations%22%3A%5B%7B%22aweme_id%22%3A%227519454908408417536%22%2C%22is_ad%22%3A0%2C%22is_ad_click%22%3A0%2C%22is_enter_detail%22%3A0%2C%22is_like%22%3A0%2C%22play_count%22%3A0%2C%22play_duration%22%3A0%2C%22play_percent%22%3A0.0%7D%2C%7B%22aweme_id%22%3A%227483803805042085160%22%2C%22is_ad%22%3A0%2C%22is_ad_click%22%3A0%2C%22is_enter_detail%22%3A0%2C%22is_like%22%3A0%2C%22play_count%22%3A0%2C%22play_duration%22%3A0%2C%22play_percent%22%3A0.0%7D%2C%7B%22aweme_id%22%3A%227525658902320401727%22%2C%22is_ad%22%3A0%2C%22is_ad_click%22%3A0%2C%22is_enter_detail%22%3A0%2C%22is_like%22%3A0%2C%22play_count%22%3A0%2C%22play_duration%22%3A0%2C%22play_percent%22%3A0.0%7D%5D%2C%22loadmore_type%22%3A0%7D&recent_items=%5B%7B%22aweme_id%22%3A%22956260147%22%2C%22item_pitaya_param%22%3A%7B%7D%2C%22doc_type%22%3A105%2C%22provider_doc_id%22%3A7553988519480266003%2C%22is_single_range%22%3Atrue%7D%2C%7B%22aweme_id%22%3A%221463459504%22%2C%22item_pitaya_param%22%3A%7B%7D%2C%22doc_type%22%3A303%2C%22provider_doc_id%22%3A7483803805042085160%2C%22is_single_range%22%3Atrue%7D%2C%7B%22aweme_id%22%3A%22-784237457%22%2C%22item_pitaya_param%22%3A%7B%22engine_ecpm%22%3A-10%2C%22req_id%22%3A%22202509261113415E4D75EF3137A25D6A70%22%2C%22search_id%22%3A%22202509261113415E4D75EF3137A25D6A70%22%2C%22doc_stay_time%22%3A-10%2C%22ad_gap%22%3A5%2C%22is_async_ad%22%3Afalse%2C%22is_douplus_ad%22%3A0%2C%22id%22%3A7525658902320401408%2C%22is_ad%22%3A0%7D%2C%22doc_type%22%3A303%2C%22provider_doc_id%22%3A7525658902320401727%2C%22is_single_range%22%3Atrue%7D%2C%7B%22aweme_id%22%3A%22897095117%22%2C%22item_pitaya_param%22%3A%7B%7D%2C%22doc_type%22%3A108%2C%22provider_doc_id%22%3A6916887821799068934%2C%22is_single_range%22%3Atrue%7D%5D&disable_general_performance_opt_from_client=1&location_permission=0&disable_server_forecast=0&cursor=0&client_engine_extra=%7B%22task_type%22%3A%22%22%2C%22is_ad_coin%22%3A%220%22%2C%22is_ecom_coin%22%3A%220%22%2C%22is_coin_new%22%3A%222%22%7D&anchor_item_id=&double_column_mode=0&is_after_locate=false&is_pull_refresh=0&is_filter_search=0&location_access=2&general_search_layout_type=2&client_extra=%7B%22charging%22%3Afalse%2C%22qoe%22%3A53%2C%22har_info%22%3A%7B%7D%7D&poi_search_info=&search_session_id=13ddcb7e-9f2d-49be-a6a2-ccb4abc33bdc&no_trace_search_switch=off&nice_search_type=general&music_format_type=1&client_height=851&goods_info_count=10&loadmore_rerank=2&double_column_experience_optimize=2&user_avatar_shrink=&enter_from_second=&client_width=393&token=search&search_request_id=202509261113415E4D75EF3137A25D6A70&search_id=202509261113415E4D75EF3137A25D6A70&disable_double_column=0&disable_hotspot_new_card=0&is_quality_style=1&is_double_column_left=0&search_rerank_info=%7B%7D&device_score=8.7522"
hea = {
'x-ss-stub': md5(payload.encode()).hexdigest().upper(),
'sdk-version': '2',
'passport-sdk-version': '203268',
'x-vc-bdturing-sdk-version': '3.7.3.cn',
'x-tt-store-region': 'cn-bj',
'x-tt-store-region-src': 'did',
'user-agent': 'com.ss.android.ugc.aweme/310801 (Linux; U; Android 10; zh_CN; MI 9; Build/QKQ1.190825.002; Cronet/TTNetVersion:b714bfef 2024-09-13 QuicVersion:c459d547 2024-08-27)',
'content-type': 'application/x-www-form-urlencoded; charset=UTF-8'
}
data = {
"url": url,
"header_list": convert_headers_to_java_format(hea)
}
r = requests.post(apiurl, headers={'Content-Type': 'application/json'}, json=data)
hea.update(r.json())
response = requests.request("POST", url, headers=hea, data=payload)
business_data = response.json().get("business_data")
if business_data:
if len(business_data) > 0:
return True
return False
else:
logger.error(response.json())
return False
class Counter:
def __init__(self):
# 用来记录每个客户端 IP 的请求次数
self.ip_keyword_count = {}
self.ip_userId_count = {}
self.redis_conn = Redis(host="172.16.0.24", password="aiyingli@@123", db=3, decode_responses=True)
self.redis_conn2 = Redis(host="172.16.0.24", password="aiyingli@@123", db=2, decode_responses=True)
self.redis_conn4 = Redis(host="172.16.0.24", password="aiyingli@@123", db=4, decode_responses=True)
def response(self, flow: mitmproxy.http.HTTPFlow):
if "/captcha/get" in flow.request.url:
device_ip = flow.client_conn.peername[0]
data = flow.response.json().get("data")
# logger.success(data)
mode = data.get("mode")
logger.info(f"{device_ip} 当前遇到验证 验证类型位:{mode}")
status = self.redis_conn4.hget("dy_app_auto_status", device_ip)
self.redis_conn4.hset("dy_app_auto_status", device_ip, mode)
if mode == "slide":
backend_img = data.get("question").get("url1")
slide_img = data.get("question").get("url2")
ocr_data = verify("20111", get_image_data(backend_img).decode(), get_image_data(slide_img).decode())
# print(ocr_data)
if ocr_data.get("code") == 10000:
value = int(ocr_data.get("data").get("data"))
logger.info(f"{device_ip} 获取坐标成功 坐标为:{value} cyfreso:{data.get('cyfreso')}")
value = value + data.get('cyfreso')
logger.info(f"修复后的value坐标为:{value}")
self.redis_conn4.hset("dy_app_auto_address", device_ip, str(value))
else:
logger.error(ocr_data)
# 开始获取坐标
elif mode == "whirl":
out_img = data.get("question").get("url1")
inner_img = data.get("question").get("url2")
data = verify("90015", get_image_data(out_img).decode(), get_image_data(inner_img).decode())
if data.get("code") == 10000:
slide_px = data.get('data').get("data").get("slide_px")
rotate_angle = data.get('data').get("data").get("rotate_angle")
self.redis_conn4.hset("dy_app_auto_address", device_ip, str(slide_px + rotate_angle))
elif "/captcha/verify" in flow.request.url:
print(flow.response.json())
device_ip = flow.client_conn.peername[0]
code = flow.response.json().get("code")
if code == 502:
logger.error(f"{device_ip} {flow.response.json().get('message')}")
self.redis_conn4.hset("dy_app_auto_status", device_ip, 'verify_error')
elif code == 200:
logger.success(f"{device_ip} 设备滑块成功 设置状态为 verify_success")
device_id, iid = extract_params_from_url(flow.request.url)
logger.success(f"{device_id} {iid} 当前设备注册完成 加入数据库中 等待搜索测试")
self.redis_conn4.sadd(f"dy_device_android_1128_{xxx(time.time())}", json.dumps({"device_id": device_id, "iid": iid}))
self.redis_conn4.hset("dy_app_auto_status", device_ip, 'verify_success')
elif code == 500:
logger.error(f"{device_ip} {flow.response.json().get('data').get('msg')}")
self.redis_conn4.hset("dy_app_auto_status", device_ip, 'verify_fail')
addons = [
Counter()
]
# mitmdump -s device_register_intercept.py -q --listen-host 0.0.0.0 --listen-port 8082 --set block_global=false
<?xml version='1.0' encoding='UTF-8' standalone='yes' ?>
<hierarchy rotation="0">
<node index="0" text="" resource-id="" class="android.widget.FrameLayout" package="com.iflytek.inputmethod.miui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[0,1209][1080,2118]" drawing-order="0" hint="">
<node index="0" text="" resource-id="" class="android.widget.LinearLayout" package="com.iflytek.inputmethod.miui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[0,1209][1080,2118]" drawing-order="1" hint="">
<node index="0" text="" resource-id="android:id/content" class="android.widget.FrameLayout" package="com.iflytek.inputmethod.miui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[0,1209][1080,2118]" drawing-order="2" hint="">
<node index="0" text="" resource-id="android:id/parentPanel" class="android.widget.LinearLayout" package="com.iflytek.inputmethod.miui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[0,1209][1080,2118]" drawing-order="1" hint="">
<node index="1" text="" resource-id="android:id/inputArea" class="android.widget.FrameLayout" package="com.iflytek.inputmethod.miui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[0,1209][1080,2118]" drawing-order="2" hint="">
<node index="0" text="" resource-id="" class="android.view.ViewGroup" package="com.iflytek.inputmethod.miui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[0,1209][1080,2118]" drawing-order="1" hint="">
<node index="0" text="" resource-id="com.iflytek.inputmethod.miui:id/input_floatable_layout" class="android.widget.LinearLayout" package="com.iflytek.inputmethod.miui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[0,1209][1080,2118]" drawing-order="1" hint="">
<node index="0" text="" resource-id="com.iflytek.inputmethod.miui:id/input_content_view" class="android.widget.FrameLayout" package="com.iflytek.inputmethod.miui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[0,1209][1080,2118]" drawing-order="2" hint="">
<node index="0" text="" resource-id="com.iflytek.inputmethod.miui:id/input_content_linear_layout" class="android.widget.LinearLayout" package="com.iflytek.inputmethod.miui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[0,1209][1080,2118]" drawing-order="1" hint="">
<node index="0" text="" resource-id="" class="android.widget.LinearLayout" package="com.iflytek.inputmethod.miui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[0,1209][1080,1347]" drawing-order="1" hint="">
<node index="0" text="" resource-id="" class="android.view.View" package="com.iflytek.inputmethod.miui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[0,1209][1080,1212]" drawing-order="1" hint="" />
<node index="1" text="" resource-id="com.iflytek.inputmethod.miui:id/speech_intensive_view" class="android.widget.LinearLayout" package="com.iflytek.inputmethod.miui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[83,1231][997,1325]" drawing-order="2" hint="">
<node index="0" text="" resource-id="" class="android.widget.ImageView" package="com.iflytek.inputmethod.miui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[306,1256][350,1300]" drawing-order="1" hint="" />
<node index="1" text="按住 说出想搜索的内容" resource-id="" class="android.widget.TextView" package="com.iflytek.inputmethod.miui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[372,1252][773,1304]" drawing-order="2" hint="" />
</node>
</node>
<node index="1" text="" resource-id="com.iflytek.inputmethod.miui:id/input_grid_root" class="android.view.View" package="com.iflytek.inputmethod.miui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[0,1347][1080,2118]" drawing-order="2" hint="" />
</node>
</node>
</node>
</node>
</node>
</node>
</node>
</node>
<node index="1" text="" resource-id="android:id/navigationBarBackground" class="android.view.View" package="com.iflytek.inputmethod.miui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[0,2118][1080,2248]" drawing-order="2" hint="" />
</node>
<node index="0" text="" resource-id="" class="android.widget.FrameLayout" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[0,0][1080,89]" drawing-order="0" hint="">
<node index="1" text="" resource-id="com.android.systemui:id/scrim_behind" class="android.view.View" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[0,0][1080,89]" drawing-order="2" hint="" />
<node index="2" text="" resource-id="com.android.systemui:id/scrim_in_front" class="android.view.View" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[0,0][1080,89]" drawing-order="9" hint="" />
<node index="3" text="" resource-id="" class="android.view.View" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[0,0][1080,89]" drawing-order="11" hint="" />
<node index="4" text="" resource-id="com.android.systemui:id/status_bar_container" class="android.widget.FrameLayout" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[0,0][1080,89]" drawing-order="4" hint="">
<node index="0" text="" resource-id="com.android.systemui:id/status_bar" class="android.widget.FrameLayout" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[0,0][1080,89]" drawing-order="1" hint="">
<node index="0" text="" resource-id="com.android.systemui:id/phone_status_bar_contents_container" class="android.widget.LinearLayout" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[19,0][1061,89]" drawing-order="3" hint="">
<node index="0" text="" resource-id="com.android.systemui:id/clock_container" class="android.widget.FrameLayout" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[27,6][231,89]" drawing-order="1" hint="">
<node index="0" text="" resource-id="com.android.systemui:id/leftside" class="android.widget.LinearLayout" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[27,6][231,89]" drawing-order="1" hint="">
<node index="0" text="9:23" resource-id="com.android.systemui:id/clock" class="android.widget.TextView" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[27,6][118,89]" drawing-order="10" hint="" />
<node index="2" text="" resource-id="com.android.systemui:id/notification_icon_area" class="android.widget.FrameLayout" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[118,6][231,89]" drawing-order="12" hint="">
<node index="0" text="" resource-id="com.android.systemui:id/notification_icon_area_inner" class="android.widget.LinearLayout" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[118,6][231,89]" drawing-order="1" hint="">
<node index="0" text="" resource-id="com.android.systemui:id/notificationIcons" class="android.widget.FrameLayout" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[118,6][231,89]" drawing-order="1" hint="">
<node index="0" text="" resource-id="" class="android.widget.ImageView" package="com.android.systemui" content-desc="Android 系统通知:已安装证书授权中心" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[218,29][231,65]" drawing-order="16" hint="" />
<node index="1" text="" resource-id="" class="android.widget.ImageView" package="com.android.systemui" content-desc="小米云服务通知:您的数据有丢失风险,建议备份" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[218,29][231,65]" drawing-order="7" hint="" />
<node index="2" text="" resource-id="" class="android.widget.ImageView" package="com.android.systemui" content-desc="查找手机通知:建议开启查找手机" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[218,29][231,65]" drawing-order="15" hint="" />
<node index="3" text="" resource-id="" class="android.widget.ImageView" package="com.android.systemui" content-desc="夸克通知:头条" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[218,29][231,65]" drawing-order="14" hint="" />
<node index="4" text="" resource-id="" class="android.widget.ImageView" package="com.android.systemui" content-desc="夸克通知:头条" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[218,29][231,65]" drawing-order="13" hint="" />
<node index="5" text="" resource-id="" class="android.widget.ImageView" package="com.android.systemui" content-desc="夸克通知:头条" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[218,29][231,65]" drawing-order="12" hint="" />
<node index="6" text="" resource-id="" class="android.widget.ImageView" package="com.android.systemui" content-desc="夸克通知:头条" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[218,29][231,65]" drawing-order="11" hint="" />
<node index="7" text="" resource-id="" class="android.widget.ImageView" package="com.android.systemui" content-desc="夸克通知:头条" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[218,29][231,65]" drawing-order="10" hint="" />
<node index="8" text="" resource-id="" class="android.widget.ImageView" package="com.android.systemui" content-desc="夸克通知:头条" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[218,29][231,65]" drawing-order="9" hint="" />
<node index="9" text="" resource-id="" class="android.widget.ImageView" package="com.android.systemui" content-desc="夸克通知:头条" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[218,29][231,65]" drawing-order="8" hint="" />
<node index="10" text="" resource-id="" class="android.widget.ImageView" package="com.android.systemui" content-desc="夸克通知:头条" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[218,29][231,65]" drawing-order="6" hint="" />
<node index="11" text="" resource-id="" class="android.widget.ImageView" package="com.android.systemui" content-desc="夸克通知:头条" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[218,29][231,65]" drawing-order="5" hint="" />
<node index="12" text="" resource-id="" class="android.widget.ImageView" package="com.android.systemui" content-desc="夸克通知:头条" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[218,29][231,65]" drawing-order="4" hint="" />
<node index="13" text="" resource-id="" class="android.widget.ImageView" package="com.android.systemui" content-desc="应用商店通知:82%的用户已更新这73款应用" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[218,29][231,65]" drawing-order="3" hint="" />
<node index="14" text="" resource-id="" class="android.widget.ImageView" package="com.android.systemui" content-desc="应用商店通知:抖音有新版本啦~" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[168,29][218,65]" drawing-order="2" hint="" />
<node index="15" text="" resource-id="" class="android.widget.ImageView" package="com.android.systemui" content-desc="Android 系统通知:选择输入法" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[118,29][168,65]" drawing-order="1" hint="" />
</node>
</node>
</node>
</node>
</node>
<node index="1" text="" resource-id="" class="android.widget.FrameLayout" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[231,6][847,89]" drawing-order="2" hint="" />
<node index="2" text="" resource-id="com.android.systemui:id/system_icon_area" class="android.widget.LinearLayout" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[847,6][1049,89]" drawing-order="3" hint="">
<node index="0" text="" resource-id="com.android.systemui:id/system_icons" class="android.widget.LinearLayout" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="true" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[847,17][1049,77]" drawing-order="1" hint="">
<node index="0" text="" resource-id="com.android.systemui:id/signal_cluster_view" class="android.widget.LinearLayout" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[847,17][965,77]" drawing-order="5" hint="">
<node index="0" text="" resource-id="com.android.systemui:id/signal_cluster" class="android.widget.LinearLayout" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="true" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[847,17][965,77]" drawing-order="1" hint="">
<node index="0" text="" resource-id="com.android.systemui:id/mobile_signal_group_dual_notch" class="android.widget.LinearLayout" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="true" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[847,17][857,77]" drawing-order="9" hint="">
<node index="0" text="" resource-id="com.android.systemui:id/mobile_combo" class="android.widget.LinearLayout" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[847,17][857,77]" drawing-order="1" hint="">
<node index="1" text="" resource-id="com.android.systemui:id/notch_carrier" class="android.widget.TextView" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[847,17][852,77]" drawing-order="2" hint="" />
<node index="2" text="" resource-id="com.android.systemui:id/mobile_type" class="android.widget.TextView" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[852,17][857,77]" drawing-order="3" hint="" />
</node>
</node>
<node index="3" text="" resource-id="com.android.systemui:id/no_sims" class="android.widget.ImageView" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[857,19][907,75]" drawing-order="10" hint="" />
<node index="4" text="" resource-id="com.android.systemui:id/wifi_combo" class="android.widget.FrameLayout" package="com.android.systemui" content-desc="WLAN 信号满格。" checkable="false" checked="false" clickable="false" enabled="true" focusable="true" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[907,19][965,75]" drawing-order="14" hint="">
<node index="0" text="" resource-id="com.android.systemui:id/wifi_signal" class="android.widget.ImageView" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[907,19][965,75]" drawing-order="1" hint="" />
<node index="1" text="" resource-id="com.android.systemui:id/wifi_inout" class="android.widget.ImageView" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[939,19][965,75]" drawing-order="3" hint="" />
</node>
</node>
</node>
<node index="1" text="" resource-id="com.android.systemui:id/battery" class="android.widget.LinearLayout" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="true" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[965,17][1049,77]" drawing-order="6" hint="">
<node index="0" text="" resource-id="" class="android.widget.FrameLayout" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[965,19][1049,75]" drawing-order="1" hint="">
<node index="0" text="" resource-id="com.android.systemui:id/battery_image" class="android.widget.ImageView" package="com.android.systemui" content-desc="正在充电,已完成百分之100。" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[965,19][1049,75]" drawing-order="1" hint="" />
<node index="1" text="100" resource-id="com.android.systemui:id/battery_digit" class="android.widget.TextView" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[985,19][1023,75]" drawing-order="3" hint="" />
</node>
</node>
</node>
</node>
</node>
</node>
</node>
</node>
<node index="0" text="" resource-id="" class="android.view.View" package="com.miui.securitycenter" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[0,368][35,608]" drawing-order="0" hint="" />
<node index="0" text="" resource-id="" class="android.widget.LinearLayout" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[0,2118][1080,2248]" drawing-order="0" hint="">
<node index="0" text="" resource-id="com.android.systemui:id/rot0" class="android.widget.FrameLayout" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[0,2118][1080,2248]" drawing-order="1" hint="">
<node index="0" text="" resource-id="com.android.systemui:id/deadzone" class="android.view.View" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[0,2118][1080,2248]" drawing-order="3" hint="" />
<node index="1" text="" resource-id="com.android.systemui:id/nav_buttons" class="android.widget.LinearLayout" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[0,2118][1080,2248]" drawing-order="1" hint="">
<node index="0" text="" resource-id="com.android.systemui:id/start_padding" class="android.widget.FrameLayout" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[0,2118][233,2248]" drawing-order="1" hint="" />
<node index="1" text="" resource-id="com.android.systemui:id/recent_apps" class="android.widget.ImageView" package="com.android.systemui" content-desc="概览" checkable="false" checked="false" clickable="true" enabled="true" focusable="true" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[233,2118][398,2248]" drawing-order="2" hint="" />
<node index="2" text="" resource-id="com.android.systemui:id/home" class="android.widget.ImageView" package="com.android.systemui" content-desc="主屏幕" checkable="false" checked="false" clickable="true" enabled="true" focusable="true" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[457,2118][622,2248]" drawing-order="4" hint="" />
<node index="3" text="" resource-id="com.android.systemui:id/back" class="android.widget.ImageView" package="com.android.systemui" content-desc="返回" checkable="false" checked="false" clickable="true" enabled="true" focusable="true" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[681,2118][846,2248]" drawing-order="6" hint="" />
<node index="4" text="" resource-id="com.android.systemui:id/side_padding" class="android.widget.FrameLayout" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[846,2118][1080,2248]" drawing-order="7" hint="" />
</node>
</node>
</node>
<node index="0" text="" resource-id="" class="android.widget.FrameLayout" package="com.ss.android.ugc.aweme" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[490,199][926,345]" drawing-order="0" hint="">
<node index="0" text="" resource-id="" class="android.widget.LinearLayout" package="com.ss.android.ugc.aweme" content-desc="" checkable="false" checked="false" clickable="true" enabled="true" focusable="true" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[490,199][926,345]" drawing-order="1" hint="">
<node index="0" text="扫一扫支持识万物啦" resource-id="" class="android.widget.TextView" package="com.ss.android.ugc.aweme" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[537,246][879,298]" drawing-order="1" hint="" />
</node>
</node>
<node index="0" text="" resource-id="" class="android.widget.FrameLayout" package="com.ss.android.ugc.aweme" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[0,0][1080,2248]" drawing-order="0" hint="">
<node index="0" text="" resource-id="" class="android.widget.LinearLayout" package="com.ss.android.ugc.aweme" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[0,0][1080,2118]" drawing-order="1" hint="">
<node index="0" text="" resource-id="android:id/content" class="android.widget.FrameLayout" package="com.ss.android.ugc.aweme" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[0,0][1080,2118]" drawing-order="2" hint="">
<node index="0" text="" resource-id="com.ss.android.ugc.aweme:id/g3" class="android.widget.FrameLayout" package="com.ss.android.ugc.aweme" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[0,0][1080,2118]" drawing-order="2" hint="">
<node index="0" text="" resource-id="com.ss.android.ugc.aweme:id/ja5" class="android.widget.FrameLayout" package="com.ss.android.ugc.aweme" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[0,0][1080,2118]" drawing-order="2" hint="" />
<node index="1" text="" resource-id="com.ss.android.ugc.aweme:id/hmy" class="android.widget.FrameLayout" package="com.ss.android.ugc.aweme" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[0,0][1080,2118]" drawing-order="1" hint="">
<node index="0" text="" resource-id="com.ss.android.ugc.aweme:id/iwr" class="android.widget.FrameLayout" package="com.ss.android.ugc.aweme" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[0,0][1080,2118]" drawing-order="1" hint="">
<node index="2" text="" resource-id="com.ss.android.ugc.aweme:id/rgu" class="android.widget.LinearLayout" package="com.ss.android.ugc.aweme" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[0,0][1080,2118]" drawing-order="6" hint="">
<node index="0" text="" resource-id="com.ss.android.ugc.aweme:id/zwc" class="android.widget.RelativeLayout" package="com.ss.android.ugc.aweme" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[0,0][1080,210]" drawing-order="1" hint="">
<node index="1" text="" resource-id="com.ss.android.ugc.aweme:id/val" class="android.widget.RelativeLayout" package="com.ss.android.ugc.aweme" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[0,89][1080,210]" drawing-order="2" hint="">
<node index="0" text="" resource-id="com.ss.android.ugc.aweme:id/vam" class="android.widget.FrameLayout" package="com.ss.android.ugc.aweme" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[0,89][1080,210]" drawing-order="1" hint="" />
<node index="1" text="" resource-id="com.ss.android.ugc.aweme:id/a=l" class="android.widget.FrameLayout" package="com.ss.android.ugc.aweme" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[0,116][132,182]" drawing-order="2" hint="">
<node index="0" text="" resource-id="com.ss.android.ugc.aweme:id/a=k" class="android.widget.ImageView" package="com.ss.android.ugc.aweme" content-desc="返回" checkable="false" checked="false" clickable="true" enabled="true" focusable="true" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[44,116][110,182]" drawing-order="1" hint="" />
</node>
<node index="2" text="" resource-id="com.ss.android.ugc.aweme:id/fl_intput_hint_container" class="android.widget.FrameLayout" package="com.ss.android.ugc.aweme" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[132,100][910,199]" drawing-order="4" hint="">
<node index="0" text="02" resource-id="com.ss.android.ugc.aweme:id/et_search_kw" class="android.widget.EditText" package="com.ss.android.ugc.aweme" content-desc="" checkable="false" checked="false" clickable="true" enabled="true" focusable="true" focused="true" scrollable="false" long-clickable="true" password="false" selected="false" visible-to-user="true" bounds="[132,100][910,199]" drawing-order="2" hint="" />
<node index="1" text="" resource-id="com.ss.android.ugc.aweme:id/kcc" class="android.widget.ImageView" package="com.ss.android.ugc.aweme" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[143,116][209,182]" drawing-order="1" hint="" />
<node index="2" text="" resource-id="" class="android.widget.LinearLayout" package="com.ss.android.ugc.aweme" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[833,127][910,171]" drawing-order="4" hint="">
<node index="0" text="" resource-id="com.ss.android.ugc.aweme:id/btn_clear" class="android.widget.ImageButton" package="com.ss.android.ugc.aweme" content-desc="清空" checkable="false" checked="false" clickable="true" enabled="true" focusable="true" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[833,127][877,171]" drawing-order="1" hint="" />
</node>
</node>
<node index="3" text="搜索" resource-id="com.ss.android.ugc.aweme:id/15i" class="android.widget.TextView" package="com.ss.android.ugc.aweme" content-desc="搜索" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[910,89][1080,210]" drawing-order="3" hint="" />
</node>
</node>
<node index="1" text="" resource-id="com.ss.android.ugc.aweme:id/iv8" class="android.widget.FrameLayout" package="com.ss.android.ugc.aweme" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[0,210][1080,2118]" drawing-order="2" hint="">
<node index="0" text="" resource-id="com.ss.android.ugc.aweme:id/v86" class="android.widget.FrameLayout" package="com.ss.android.ugc.aweme" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[0,210][1080,2118]" drawing-order="2" hint="">
<node index="0" text="" resource-id="com.ss.android.ugc.aweme:id/vc6" class="android.widget.RelativeLayout" package="com.ss.android.ugc.aweme" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[0,210][1080,2118]" drawing-order="1" hint="">
<node index="0" text="" resource-id="com.ss.android.ugc.aweme:id/v87" class="android.view.View" package="com.ss.android.ugc.aweme" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[0,210][1080,2118]" drawing-order="1" hint="" />
<node index="1" text="" resource-id="com.ss.android.ugc.aweme:id/recycler_view" class="androidx.recyclerview.widget.RecyclerView" package="com.ss.android.ugc.aweme" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="true" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[0,210][1080,2118]" drawing-order="3" hint="" />
</node>
</node>
</node>
</node>
<node index="3" text="" resource-id="com.ss.android.ugc.aweme:id/3v1" class="android.view.ViewGroup" package="com.ss.android.ugc.aweme" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[0,0][1080,2118]" drawing-order="7" hint="" />
</node>
</node>
</node>
<node index="1" text="" resource-id="com.ss.android.ugc.aweme:id/action_bar_root" class="android.widget.LinearLayout" package="com.ss.android.ugc.aweme" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[0,0][1080,2118]" drawing-order="1" hint="">
<node index="0" text="" resource-id="" class="android.widget.FrameLayout" package="com.ss.android.ugc.aweme" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[0,0][1080,2118]" drawing-order="2" hint="" />
</node>
</node>
</node>
</node>
</hierarchy>
\ No newline at end of file
import asyncio
import json
import os
import random
import re
import time
import requests
from playwright.async_api import async_playwright, TimeoutError
from loguru import logger
from redis.asyncio import Redis
common_redis0 = Redis(host='172.16.0.24', password="aiyingli@@123", port=6379, db=0, decode_responses=True)
common_redis2 = Redis(host='172.16.0.24', password="aiyingli@@123", port=6379, db=2, decode_responses=True)
common_redis3 = Redis(host='172.16.0.24', password="aiyingli@@123", port=6379, db=3, decode_responses=True)
# 15321516159
async def alert(msg):
url = "https://open.feishu.cn/open-apis/bot/v2/hook/1d0aa56a-ed39-4128-b445-ba953b32444b"
payload = {
"msg_type": "text",
"content": {
"text": msg
}
}
try:
resp = requests.post(
url,
json=payload,
headers={"Content-Type": "application/json"},
timeout=10
)
resp.raise_for_status()
logger.info("Feishu alert sent, status=%s", resp.status_code)
except requests.RequestException as e:
logger.error("Feishu alert failed: %s", e)
account_list = ["15313110635"]
# 18731654852
# 全局变量
MAX_INTERCEPT_COUNT = 5 # 最多拦截5次
spider_task_count = 0
MAX_RETRIES = 3 # 最大重试次数
TIMEOUT = 60000 # 超时时间60秒
search_notes_count_lock = asyncio.Lock() # 计数器锁
search_notes_count = 0 # 重置为0开始计数
account_status = {}
def extract_and_parse_json(html: str) -> str:
pattern = r'__INITIAL_STATE__\s*=\s*({[\s\S]*?})\s*;?\s*</script>'
match = re.search(pattern, html)
# 错误处理
if not match or len(match.groups()) < 1:
logger.success(html)
logger.error("未找到匹配的JSON数据")
return ""
# 2. 清理JSON字符串
json_str = match.group(1).replace("undefined", "null")
return json_str
async def handle_response(response,page, context, cursor):
if "xiaohongshu.com/explore" in response.url:
text = await response.text()
data_json = extract_and_parse_json(text)
if data_json:
feeds = json.loads(data_json).get("feed").get("feeds")
pipeline = common_redis2.pipeline()
await pipeline.delete("xhs_app:xsec_token")
for i in feeds:
xsecToken = i.get("xsecToken")
if xsecToken:
await pipeline.sadd("xhs_app:xsec_token",xsecToken)
await pipeline.execute()
await pipeline.aclose()
async def launch_browser():
playwright = await async_playwright().start()
context = await playwright.chromium.launch(
headless=False,
args=[
"--window-size=800,600",
# "--start-maximized"
"--disable-gpu",
],
)
page = await context.new_page()
page.set_default_timeout(10000)
await page.add_init_script("""
Object.defineProperty(navigator, 'webdriver', {
get: () => undefined
});
window.navigator.chrome = { runtime: {} };
""")
# await page.route("**/*", lambda route: route.abort()
# if route.request.resource_type == "image"
# else route.continue_())
await asyncio.sleep(1) # 等待 profile 锁释放
return playwright, context, page
async def search(account):
global account_status, search_notes_count, spider_task_count
account_status[account] = "online"
playwright, context, page = await launch_browser()
cursor = False
page.on("response", lambda response: asyncio.create_task(
handle_response(response, page, context, cursor)
))
while True:
await page.goto(f"https://www.xiaohongshu.com/explore")
await page.wait_for_selector(".feeds-container", state="attached", timeout=5000)
time.sleep(3600)
async def main():
account_tasks = [search(acc) for acc in account_list]
await asyncio.gather(*account_tasks)
if __name__ == '__main__':
asyncio.run(main())
function hookUrl() {
try {
var URL = Java.use('java.net.URL');
// hook 所有常见的重载构造函数
// 1. new URL(String spec)
URL.$init.overload('java.lang.String').implementation = function (spec) {
var url = this.$init(spec);
printUrlStack('URL(String)', spec);
return url;
};
// // 2. new URL(String protocol, String host, String file)
// URL.$init.overload('java.lang.String', 'java.lang.String', 'java.lang.String').implementation = function (protocol, host, file) {
// var fullUrl = protocol + "://" + host + file;
// var url = this.$init(protocol, host, file);
// printUrlStack('URL(protocol, host, file)', fullUrl);
// return url;
// };
//
// // 3. new URL(String protocol, String host, int port, String file)
// URL.$init.overload('java.lang.String', 'java.lang.String', 'int', 'java.lang.String').implementation = function (protocol, host, port, file) {
// var fullUrl = protocol + "://" + host + ":" + port + file;
// var url = this.$init(protocol, host, port, file);
// printUrlStack('URL(protocol, host, port, file)', fullUrl);
// return url;
// };
//
// // 4. new URL(URL context, String spec)
// URL.$init.overload('java.net.URL', 'java.lang.String').implementation = function (context, spec) {
// var fullUrl = context.toString() + " -> " + spec;
// var url = this.$init(context, spec);
// printUrlStack('URL(context, spec)', fullUrl);
// return url;
// };
// 其他可能的 overload(较少用,但保险起见)
if (URL.$init.overloads.length > 4) {
// console.log('[+] Found additional URL constructors: ' + URL.$init.overloads.length);
}
// console.log('[+] java.net.URL constructors hooked successfully!');
} catch (e) {
// console.log('[-] Hook java.net.URL failed: ' + e);
// console.log(e.stack);
}
// 通用打印堆栈函数
function printUrlStack(constructorType, urlString) {
// console.log('\n=== [New URL Created] ===');
// console.log('Constructor: ' + constructorType);
// console.log('URL: ' + urlString);
// 打印 Java 堆栈
var thread = Java.use('java.lang.Thread').currentThread();
var stackTrace = thread.getStackTrace();
if (stackTrace !== null) {
// console.log('Java Stack Trace:');
for (var i = 0; i < stackTrace.length; i++) {
var element = stackTrace[i];
// console.log(' at ' + element.getClassName() + '.' + element.getMethodName() +
// '(' + element.getFileName() + ':' + element.getLineNumber() + ')');
}
} else {
// console.log(' <Stack trace unavailable>');
}
// console.log('============================\n');
}
}
function main() {
Java.perform(function () {
Interceptor.attach(Module.findExportByName(null, 'android_dlopen_ext'), {
onEnter: function (args) {
var path = args[0].readCString();
if (path && (path.indexOf('msaoaidsec') !== -1)) {
// console.log('[+] Blocking load: ' + path);
args[0] = ptr(0); // 把路径改成 NULL,阻止加载
// console.log('[+] libmsaoaidsec.so loaded: ' + path);
}
}
});
// console.log('Anti-Frida bypass loaded!');
});
hook_xhs();
}
function hook_xhs() {
'use strict';
Java.perform(function () {
try {
var RealInterceptorChain = Java.use("okhttp3.internal.http.RealInterceptorChain");
var ArrayList = Java.use("java.util.ArrayList")
RealInterceptorChain.proceed.overload('okhttp3.Request').implementation = function (request) {
var url = request.url().toString();
if (url.indexOf("/api/sns/v10/search/notes") !== -1) {
var headers = request.headers();
var customIPList = headers.get("X-XHS-Ext-CustomIPList");
if (customIPList !== null) {
try {
// 使用反射获取私有字段
var chainField = this.class.getDeclaredField("interceptors");
chainField.setAccessible(true);
var interceptors = chainField.get(this); // List<Interceptor>
var indexField = this.class.getDeclaredField("index");
indexField.setAccessible(true);
var currentIndex = indexField.get(this); // int
var callsField = this.class.getDeclaredField("calls");
callsField.setAccessible(true);
var calls = callsField.get(this); // int,记录当前拦截器已调用次数
var interceptor_list = Java.cast(interceptors, ArrayList);
// console.log("\n┌────────────────────────────────────────");
// // console.log("│ [拦截器链信息] 当前请求: " + url);
// console.log("│ 当前拦截器索引: " + currentIndex + " (已调用次数: " + calls + ")");
// console.log("│ 拦截器链总数量: " + interceptor_list.size());
// 遍历所有拦截器并打印类名
for (var i = 0; i < interceptor_list.size(); i++) {
var interceptor = interceptor_list.get(i);
var className = interceptor ? interceptor.$className : "null";
var marker = (i === currentIndex) ? " ← 当前正在执行" : "";
// console.log("│ [" + i + "] " + className + marker);
}
// console.log("└────────────────────────────────────────\n");
} catch (e) {
// console.log("│ 获取拦截器链信息失败: " + e);
}
// console.log("\n┌────────────────────────────────────────");
// console.log("│ [XHS 最终请求] 检测到 X-XHS-Ext-CustomIPList,打印完整流量");
// console.log("│ X-XHS-Ext-CustomIPList: " + customIPList);
// console.log("│ URL: " + url);
// console.log("│ Method: " + request.method());
// console.log(headers);
// 打印 Request Body
var reqBody = request.body();
if (reqBody) {
var buffer = Java.use("okio.Buffer").$new();
reqBody.writeTo(buffer);
// console.log("│ Request Body:\n" + buffer.readUtf8());
} else {
// console.log("│ Request Body: null");
}
// 执行原始请求
var response = this.proceed(request);
// 打印完整 Response
// console.log("│");
// console.log("│ Response Code: " + response.code() + " " + response.message());
var respBody = response.body();
if (respBody) {
var contentLength = respBody.contentLength();
// console.log(contentLength)
// console.log("│ Response Content-Length: " + (contentLength === -1 ? "unknown" : contentLength));
// 设置一个合理上限,防止超大响应卡死(可调整)
var MAX_SIZE = 5 * 1024 * 1024; // 5MB
if (contentLength === -1 || contentLength <= MAX_SIZE) {
try {
var fullBodyString = respBody.string(); // 读取完整 Body
var wrapper_resp = {url: url, response_body: fullBodyString, status: response.code()}
send(JSON.stringify(wrapper_resp))
// send("test message from frida");
// console.log("│ Response Body (完整,不缩减):\n" + fullBodyString);
// 重建 Body,防止 App 后续读取为空
var ResponseBody = Java.use("okhttp3.ResponseBody");
var mediaType = respBody.contentType();
var newBody = ResponseBody.create(mediaType, fullBodyString);
response = response.newBuilder().body(newBody).build();
} catch (e) {
// console.log("│ 读取完整 Body 失败: " + e);
}
} else {
// console.log("│ Response Body 过大 (" + contentLength + " bytes),超过 " + MAX_SIZE + " 字节限制,已跳过打印(可调整 MAX_SIZE)");
// 即使不打印,也要消耗并重建 Body,避免影响 App
try {
var temp = respBody.string();
var ResponseBody = Java.use("okhttp3.ResponseBody");
var newBody = ResponseBody.create(respBody.contentType(), temp);
response = response.newBuilder().body(newBody).build();
} catch (e) {
}
}
} else {
// console.log("│ Response Body: null");
}
// console.log("└────────────────────────────────────────\n");
return response;
}
}
// 其他情况直接透传
return this.proceed(request);
};
// console.log("[*] XHS Hook 已注入:有 X-XHS-Ext-CustomIPList 时完整打印 Response Body(不缩减)");
} catch (e) {
// console.log("[-] Hook 失败: " + e);
}
});
}
// frida -H 127.0.0.1:1234 -F -l okhttp.js
// frida -H 127.0.0.1:1234 -F -l okhttp.js -o log.txt
// frida -H 127.0.0.1:1234 -F -l okhttp.js --runtime=v8 --debug
main()
\ No newline at end of file
import base64
import datetime
import time
import mitmproxy.http
from mitmproxy import ctx
from loguru import logger
from urllib.parse import urlparse, parse_qs
from redis import Redis
import pymysql
from pymysql.err import OperationalError
from tools import client_account,search_clientip,user_clientip,client_proxy
from mitmproxy.net.server_spec import ServerSpec
from mitmproxy.connection import Server
class SimpleMySQL:
"""极简查询封装:只支持 SELECT * … WHERE ..."""
def __init__(self, charset="utf8mb4"):
self.cfg = dict(host="tenant-2101894307-cn-beijing-public.bytehouse.volces.com", port=3306, user="bytehouse",
password="m1wUyPHX0H:JQDqesXaoc", db="douchacha_data", charset=charset,
cursorclass=pymysql.cursors.DictCursor,
autocommit=True)
self._conn = None
self._connect()
def _connect(self):
if self._conn:
self._conn.close()
self._conn = pymysql.connect(**self.cfg)
def _reconnect(self):
try:
self._connect()
except Exception as e:
raise RuntimeError(f"Reconnect failed: {e}") from e
def _execute(self, sql):
with self._conn.cursor() as cur:
cur.execute(sql)
return cur.fetchall()
def close(self):
self._conn.close()
def _ensure_conn(self):
try:
self._conn.ping(reconnect=True) # 如果断了会自动重连
except Exception as e:
logger.error(f"MySQL ping failed, reconnecting: {e}")
self._conn = self._connect() # 你自己封装的重连逻辑
def replace_into(self, table, item_list):
self._ensure_conn()
if not item_list:
return 0
try:
keys = list(item_list[0].keys())
cols = ", ".join(f"`{k}`" for k in keys)
placeholders = ", ".join(["%s"] * len(keys))
sql = f"REPLACE INTO `{table}` ({cols}) VALUES ({placeholders})"
# 处理特殊字符
def sanitize_value(value):
if value is None:
return None
if isinstance(value, str):
# 移除或转义可能引起问题的字符
return value.replace('`', '').replace('\\', '\\\\')
return value
values = [tuple(sanitize_value(item[k]) for k in keys) for item in item_list]
try:
# 🔑 关键:写之前先 ping 一下,断了就重连
self._conn.ping(reconnect=True)
with self._conn.cursor() as cur:
cur.executemany(sql, values)
# self._conn.commit()
logger.success(f"********** {table} 共写入{len(item_list)}条数据 **********")
return len(values)
except Exception as e:
logger.error(f"MySQL 执行错误: {e}")
raise
except Exception as e:
print(f"Error: {e}")
self._connect()
def xxx(timestamp):
dt = datetime.datetime.fromtimestamp(timestamp)
# 格式化为年月日
return dt.strftime("%Y%m%d")
class Counter:
def __init__(self):
# 用来记录每个客户端 IP 的请求次数
self.db = SimpleMySQL()
self.ip_keyword_count = {}
self.ip_userId_count = {}
self.redis_conn = Redis(host="172.16.0.24", password="aiyingli@@123", db=3, decode_responses=True)
self.redis_conn2 = Redis(host="172.16.0.24", password="aiyingli@@123", db=2, decode_responses=True)
def response(self, flow: mitmproxy.http.HTTPFlow):
if "v10/search/notes" in flow.request.url:
# logger.success(flow.response.text)
try:
client_ip = flow.client_conn.peername[0]
parsed_url = urlparse(flow.request.url)
query_params = parse_qs(parsed_url.query)
keyword = query_params.get("keyword", [""])[0]
if client_ip not in self.ip_keyword_count:
self.ip_keyword_count[client_ip] = {}
if keyword not in self.ip_keyword_count[client_ip]:
self.ip_keyword_count[client_ip][keyword] = 0
self.ip_keyword_count[client_ip][keyword] += 1
count = self.ip_keyword_count[client_ip][keyword]
logger.info(f"{client_ip} {keyword} 拦截次数:{count}")
self.redis_conn.hset(f"xhs_app:{client_ip}", keyword, count)
try:
if flow.response.json().get("data"):
items = flow.response.json().get("data", {}).get("items", [])
if len(items) > 0:
item_list = []
for idx,item in enumerate(items):
model_type = item.get("model_type")
if model_type == "dsl" or model_type == "hot_query" or model_type == "questionnaire_survey" or model_type == "ads":
continue
try:
global_rank = (count - 1) * 20 + idx + 1
data_dic = {}
data_dic["key_word"] = keyword
data_dic["rank"] = global_rank
data_dic["video_id"] = item.get("note").get("id")
data_dic["update_pt"] = xxx(time.time()) + "00"
data_dic["create_pt"] = xxx(time.time())
item_list.append(data_dic)
except:
# logger.error(item.get("note"))
logger.success(f"{model_type} {item}")
self.db.replace_into("ods_aidso_monitor_video_rank_xhs", item_list)
# logger.success(items)
logger.success(f"{keyword} 拦截成功 len -> {len(items)}")
else:
logger.success(f"{keyword} 拦截失败")
self.redis_conn.hset(f"xhs_app:{client_ip}:{keyword}", keyword, "1")
else:
print(flow.response.json())
if flow.response.json().get('msg') == "访问次数已达上限,请改天再试":
self.redis_conn.hset(f"xhs_app:status:{client_ip}","status" , "infinity")
print(flow.response.json())
if flow.response.json().get("code") == 300013:
logger.error(flow.response.json())
if flow.response.json().get("code") == -100:
logger.error(flow.response.json())
print("获取data失败咯")
except Exception as e:
logger.error(f"解析 response 失败: {e}")
self.db = SimpleMySQL()
# logger.info(flow.response.text)
self.redis_conn.hset(f"xhs_app:{client_ip}:{keyword}", keyword, "0")
if count == 5:
del self.ip_keyword_count[client_ip][keyword]
logger.info(f"{client_ip} {keyword} 达到5次,已从 缓存 删除")
except Exception as e:
logger.error(f" 失败: {e}")
addons = [
Counter()
]
# python -m mitmdump -s http_lanjie_keyword.py -q --listen-host 0.0.0.0 --set block_global=false
# mitmdump -p 8082 -s http_lanjie_keyword.py -q --listen-host 0.0.0.0 --set block_global=false --mode upstream:http://180.100.203.20:16816 --upstream-auth iprowq:yk2gbxo4
\ No newline at end of file
import asyncio
import base64
import datetime
import json
import time
from concurrent.futures import ThreadPoolExecutor
from urllib.parse import urlparse, parse_qs
import mitmproxy.http
import pymysql
from loguru import logger
from mitmproxy import ctx
from mitmproxy.connection import Server
from pymysql.err import OperationalError
from redis import Redis
# ==================== 上游代理配置 ====================
MAX_BODY_LEN = 4096
REDIS_TIMEOUTS = dict(socket_connect_timeout=3, socket_timeout=3, health_check_interval=30)
xhs_list_phone = {
#"172.200.4.38": "",
#"172.200.4.24": "",
#"172.200.4.40": "http://iprowq:yk2gbxo4@36.138.65.47:16818",
#"172.200.4.43": "http://iprowq:yk2gbxo4@180.100.203.20:16816",
#"172.200.4.23": "http://iprowq:yk2gbxo4@171.15.130.199:16816",
"172.20.1.246": "http://iprowq:yk2gbxo4@103.236.63.179:16816",
"172.20.1.250": "http://iprowq:yk2gbxo4@119.96.126.55:16817",
"172.20.1.251": "http://iprowq:yk2gbxo4@36.138.65.47:16818",
"172.20.1.252": "http://iprowq:yk2gbxo4@171.15.130.199:16816",
"172.20.1.247": "http://iprowq:yk2gbxo4@211.101.232.183:16819",
"172.20.1.249": "http://iprowq:yk2gbxo4@36.212.178.35:16816",
"172.20.1.248": "http://iprowq:yk2gbxo4@180.100.203.20:16816",
}
# 备用代理(后续手动添加)
#
# http://iprowq:yk2gbxo4@211.101.232.183:16819
# http://iprowq:yk2gbxo4@182.40.33.158:16819
# http://iprowq:yk2gbxo4@218.78.109.253:16816
# http://iprowq:yk2gbxo4@27.150.190.63:16819
# http://iprowq:yk2gbxo4@36.133.175.164:16819
# http://iprowq:yk2gbxo4@222.84.255.244:16819
def _basic_auth(username: str, password: str) -> str:
token = base64.b64encode(f"{username}:{password}".encode()).decode()
return f"Basic {token}"
def _parse_proxy_url(proxy_url: str):
parsed = urlparse(proxy_url)
scheme = (parsed.scheme or "http").lower()
if scheme not in {"http", "https"}:
raise ValueError(f"unsupported upstream proxy scheme: {scheme}")
if not parsed.hostname or not parsed.port:
raise ValueError(f"invalid upstream proxy url: {proxy_url}")
auth = None
if parsed.username is not None:
auth = _basic_auth(parsed.username, parsed.password or "")
return scheme, parsed.hostname, parsed.port, auth
def _client_proxy_config(client_ip: str):
proxy_url = xhs_list_phone.get(client_ip)
if not proxy_url:
return None
return _parse_proxy_url(proxy_url)
def _client_ip(flow: mitmproxy.http.HTTPFlow) -> str:
"""Return the phone IP that opened the Wi-Fi proxy connection.
A phone configured with a Wi-Fi manual proxy still appears here as the
peer of mitmproxy; it does not need (and should not need) Android's
global proxy setting. Be defensive because peername can be unavailable
while a connection is being torn down.
"""
peername = getattr(flow.client_conn, "peername", None)
if not peername:
return "unknown"
return peername[0]
def _safe_text(message: mitmproxy.http.Message) -> str:
if not message.content:
return ""
try:
text = message.get_text(strict=False)
except Exception:
return f"<{len(message.content)} bytes binary>"
if len(text) > MAX_BODY_LEN:
return text[:MAX_BODY_LEN] + "\n...<truncated>"
return text
def _set_upstream_proxy(flow: mitmproxy.http.HTTPFlow):
client_ip = _client_ip(flow)
proxy_config = _client_proxy_config(client_ip)
if not proxy_config:
flow.metadata.pop("upstream_proxy", None)
# 未配置的手机保持直连,不继承其他 flow 的上游代理。
if flow.server_conn.timestamp_start is None:
flow.server_conn.via = None
return None
scheme, host, port, auth = proxy_config
desired_via = (scheme, (host, port))
current_via = flow.server_conn.via
already_open = flow.server_conn.timestamp_start is not None
if current_via != desired_via and already_open:
flow.server_conn = Server(
address=flow.server_conn.address,
transport_protocol=flow.server_conn.transport_protocol,
)
flow.server_conn.via = desired_via
flow.metadata["upstream_proxy"] = f"{scheme}://{host}:{port}"
return proxy_config
# ==================== MySQL 封装 ====================
class SimpleMySQL:
"""极简查询封装:只支持 SELECT * … WHERE ..."""
def __init__(self, charset="utf8mb4"):
self.cfg = dict(
host="tenant-2101894307-cn-beijing-public.bytehouse.volces.com",
port=3306,
user="bytehouse",
password="m1wUyPHX0H:JQDqesXaoc",
db="douchacha_data",
charset=charset,
cursorclass=pymysql.cursors.DictCursor,
autocommit=True,
connect_timeout=5,
read_timeout=10,
write_timeout=10,
)
self._conn = None
def _connect(self):
if self._conn:
self._conn.close()
self._conn = pymysql.connect(**self.cfg)
def _reconnect(self):
try:
self._connect()
except Exception as e:
raise RuntimeError(f"Reconnect failed: {e}") from e
def _execute(self, sql):
with self._conn.cursor() as cur:
cur.execute(sql)
return cur.fetchall()
def close(self):
if self._conn is not None:
self._conn.close()
self._conn = None
def _ensure_conn(self):
if self._conn is None:
self._connect()
return
try:
self._conn.ping(reconnect=True)
except Exception as e:
logger.error(f"MySQL ping failed, reconnecting: {e}")
self._connect()
def replace_into(self, table, item_list):
self._ensure_conn()
if not item_list:
return 0
try:
keys = list(item_list[0].keys())
cols = ", ".join(f"`{k}`" for k in keys)
placeholders = ", ".join(["%s"] * len(keys))
sql = f"REPLACE INTO `{table}` ({cols}) VALUES ({placeholders})"
def sanitize_value(value):
if value is None:
return None
if isinstance(value, str):
return value.replace("`", "").replace("\\", "\\\\")
return value
values = [tuple(sanitize_value(item[k]) for k in keys) for item in item_list]
try:
self._conn.ping(reconnect=True)
with self._conn.cursor() as cur:
cur.executemany(sql, values)
logger.success(f"********** {table} 共写入{len(item_list)}条数据 **********")
return len(values)
except Exception as e:
logger.error(f"MySQL 执行错误: {e}")
raise
except Exception as e:
logger.error(f"MySQL 写入失败 table={table}: {e}")
raise
def xxx(timestamp):
dt = datetime.datetime.fromtimestamp(timestamp)
return dt.strftime("%Y%m%d")
# ==================== 核心拦截 + 代理逻辑 ====================
class Counter:
def __init__(self):
self.db = SimpleMySQL()
self.ip_keyword_count = {}
self.ip_userId_count = {}
self.redis_conn = Redis(
host="172.16.0.24", password="aiyingli@@123", db=3, decode_responses=True, **REDIS_TIMEOUTS
)
self.redis_conn2 = Redis(
host="172.16.0.24", password="aiyingli@@123", db=2, decode_responses=True, **REDIS_TIMEOUTS
)
self.logged_proxy_clients = set()
self.diagnostic_times = {}
# 同一连接的写入保持串行,存储阻塞时其他手机请求仍能正常转发。
self._response_executor = ThreadPoolExecutor(max_workers=1, thread_name_prefix="xhs-keyword-storage")
def _close_storage(self):
for backend in (self.db, self.redis_conn, self.redis_conn2):
try:
backend.close()
except Exception as e:
logger.warning(f"关闭采集存储连接失败: {e}")
def done(self):
self._response_executor.submit(self._close_storage)
self._response_executor.shutdown(wait=False)
def _diagnostic(self, key, message):
now = time.monotonic()
if now - self.diagnostic_times.get(key, -60) >= 60:
self.diagnostic_times[key] = now
logger.info(message)
def load(self, loader) -> None:
loader.add_option("xhs_http1_compat", bool, True,
"Use HTTP/1.1 for XHS CDN responses with invalid HTTP/2 header whitespace.")
logger.info(f"mitmproxy 已加载 {len(xhs_list_phone)} 个手机上游代理映射")
for client_ip, proxy_url in xhs_list_phone.items():
try:
_, host, port, _ = _parse_proxy_url(proxy_url)
logger.info(f"手机 {client_ip} -> {host}:{port}")
except Exception as e:
logger.error(f"手机 {client_ip} 的上游代理配置无效:{e}")
def running(self):
# 实测 CDN 的 HTTP/2 响应包含非法首尾空格,导致协议错误和持续重试。
# 使用协议协商回退,不关闭证书验证或 HTTP 头安全校验。
ctx.options.update(connection_strategy="lazy")
if ctx.options.xhs_http1_compat:
ctx.options.update(http2=False)
logger.info("已启用 HTTP/1.1 兼容模式;可用 --set xhs_http1_compat=false 关闭")
def client_connected(self, client):
"""Log the source address seen by mitmproxy.
This is the quickest way to verify a Wi-Fi manual proxy: the address
must be one of the phone IPs in ``xhs_list_phone``. No Android global
proxy setting is read or changed here.
"""
peername = getattr(client, "peername", None)
self._diagnostic(("client", peername[0] if peername else None),
f"客户端已连接: {peername}")
def client_disconnected(self, client):
if client.error and client.peername:
self._diagnostic(("disconnect", client.peername[0], client.error),
f"客户端断开: {client.peername} error={client.error}")
def tls_failed_client(self, data):
self._diagnostic(("client_tls", data.context.client.peername[0], data.conn.sni),
f"客户端 TLS 失败: {data.context.client.peername} "
f"host={data.conn.sni} error={data.conn.error}")
def tls_failed_server(self, data):
self._diagnostic(("server_tls", data.conn.address),
f"上游 TLS 失败: host={data.conn.address} error={data.conn.error}")
# ----- 上游代理 hook -----
def request(self, flow: mitmproxy.http.HTTPFlow) -> None:
# 上游选择在更早的 requestheaders 中完成;CONNECT 使用独立 hook。
data = {
"type": "request",
"client_ip": _client_ip(flow),
"method": flow.request.method,
"url": flow.request.pretty_url,
"headers": dict(flow.request.headers),
# "body": _safe_text(flow.request),
}
# ctx.log.info(json.dumps(data, ensure_ascii=False))
def requestheaders(self, flow: mitmproxy.http.HTTPFlow) -> None:
client_ip = _client_ip(flow)
proxy_config = _set_upstream_proxy(flow)
if proxy_config is None:
return
_, _, _, auth = proxy_config
if auth and flow.request.scheme == "http":
flow.request.headers["Proxy-Authorization"] = auth
if client_ip not in self.logged_proxy_clients:
logger.info(
f"手机 {client_ip} 已匹配上游代理 "
f"{flow.metadata.get('upstream_proxy')}"
)
self.logged_proxy_clients.add(client_ip)
if "ipinfo.io" in flow.request.pretty_url:
logger.info(
f"ipinfo 请求:手机 {client_ip} -> "
f"{flow.metadata.get('upstream_proxy', '直连')}"
)
def http_connect_upstream(self, flow: mitmproxy.http.HTTPFlow):
client_ip = _client_ip(flow)
proxy_config = _set_upstream_proxy(flow)
if not proxy_config:
return
_, _, _, auth = proxy_config
if auth:
flow.request.headers["Proxy-Authorization"] = auth
if client_ip not in self.logged_proxy_clients:
logger.info(
f"手机 {client_ip} 已匹配上游代理 "
f"{flow.metadata.get('upstream_proxy')}"
)
self.logged_proxy_clients.add(client_ip)
if "ipinfo.io" in flow.request.pretty_url:
logger.info(
f"ipinfo 请求:手机 {client_ip} -> "
f"{flow.metadata.get('upstream_proxy', '直连')}"
)
# ----- 响应拦截 hook -----
async def response(self, flow: mitmproxy.http.HTTPFlow) -> None:
if flow.response is None or "v10/search/notes" not in flow.request.url:
return
started = time.monotonic()
try:
await asyncio.get_running_loop().run_in_executor(
self._response_executor, self._process_response, flow
)
finally:
elapsed = time.monotonic() - started
if elapsed >= 3:
logger.warning(
f"采集存储处理缓慢 client={_client_ip(flow)} elapsed={elapsed:.1f}s "
"(含排队时间),请检查 MySQL/Redis"
)
def _process_response(self, flow: mitmproxy.http.HTTPFlow) -> None:
# 不解码无关的视频、图片响应;只处理目标搜索 JSON。
if "v10/search/notes" in flow.request.url:
try:
client_ip = _client_ip(flow)
parsed_url = urlparse(flow.request.url)
query_params = parse_qs(parsed_url.query)
keyword = query_params.get("keyword", [""])[0]
if client_ip not in self.ip_keyword_count:
self.ip_keyword_count[client_ip] = {}
if keyword not in self.ip_keyword_count[client_ip]:
self.ip_keyword_count[client_ip][keyword] = 0
self.ip_keyword_count[client_ip][keyword] += 1
count = self.ip_keyword_count[client_ip][keyword]
logger.info(f"{client_ip} {keyword} 拦截次数:{count}")
self.redis_conn.hset(f"xhs_app:{client_ip}", keyword, count)
try:
if flow.response.json().get("data"):
items = flow.response.json().get("data", {}).get("items", [])
if len(items) > 0:
item_list = []
item_list_v2 = []
for idx, item in enumerate(items):
model_type = item.get("model_type")
if model_type in (
"dsl",
"hot_query",
"questionnaire_survey",
"ads",
"live",
):
continue
try:
global_rank = (count - 1) * 20 + idx + 1
data_dic = {}
data_dic["key_word"] = keyword
data_dic["rank"] = global_rank
data_dic["video_id"] = item.get("note").get("id")
data_dic["update_pt"] = xxx(time.time()) + "00"
data_dic["create_pt"] = xxx(time.time())
item_list.append(data_dic)
posted_dic_v2 = data_dic.copy()
posted_dic_v2["video_id_tag"] = data_dic["video_id"]
posted_dic_v2["video_id"] = f'{item.get("note").get("user").get("userid")}{item.get("note").get("timestamp")}'
item_list_v2.append(posted_dic_v2)
except:
# logger.success(f"{model_type} {item}")
pass
self.db.replace_into(
"ods_aidso_monitor_video_rank_xhs", item_list
)
self.db.replace_into(
"ods_aidso_monitor_video_rank_xhs_v2", item_list_v2
)
logger.success(
f"{keyword} 拦截成功 len -> {len(items)}"
)
pass
else:
# logger.success(f"{keyword} 拦截失败")
pass
self.redis_conn.hset(
f"xhs_app:{client_ip}:{keyword}", keyword, "1"
)
else:
# print(flow.response.json())
if (
flow.response.json().get("msg")
== "访问次数已达上限,请改天再试"
):
self.redis_conn.hset(
f"xhs_app:status:{client_ip}", "status", "infinity"
)
# print(flow.response.json())
# if flow.response.json().get("code") == 300013:
# logger.error(flow.response.json())
# if flow.response.json().get("code") == -100:
# logger.error(flow.response.json())
# print("获取data失败咯")
except Exception:
logger.exception(f"搜索响应处理失败 client={client_ip} keyword={keyword}")
self.redis_conn.hset(
f"xhs_app:{client_ip}:{keyword}", keyword, "0"
)
if count == 5:
del self.ip_keyword_count[client_ip][keyword]
logger.info(f"{client_ip} {keyword} 达到5次,已从 缓存 删除")
except Exception:
logger.exception(f"搜索响应处理失败 client={_client_ip(flow)}")
def error(self, flow: mitmproxy.http.HTTPFlow) -> None:
"""Report the real upstream/client error instead of only 10054 noise."""
if flow.error:
logger.warning(
f"请求失败 client={_client_ip(flow)} upstream={flow.metadata.get('upstream_proxy', '直连')} "
f"host={flow.request.host} path={urlparse(flow.request.url).path} error={flow.error}"
)
addons = [Counter()]
# 启动命令示例:
# mitmdump -q -s http_lanjie_keyword_proxy.py --listen-host 0.0.0.0 --listen-port 8901 --set confdir=./tools/.mitmproxy_simple --set block_global=false --set connection_strategy=lazy
# 注意:mitmdump 只负责监听和按手机 IP 选择上游代理,不会自动修改手机代理设置。
# 手机 Wi-Fi 手动代理指向电脑 IP:8901 即可,无需设置 Android 全局代理。
import base64
import datetime
import json
import time
from urllib.parse import urlparse, parse_qs
import mitmproxy.http
import pymysql
from loguru import logger
from mitmproxy import ctx
from mitmproxy.connection import Server
from pymysql.err import OperationalError
from redis import Redis
# ==================== 上游代理配置 ====================
MAX_BODY_LEN = 4096
xhs_list_phone = {
"172.200.4.17": "http://iprowq:yk2gbxo4@103.236.63.179:16816",
"172.200.4.38": "http://iprowq:yk2gbxo4@180.100.203.20:16816",
"172.200.4.24": "http://iprowq:yk2gbxo4@223.247.138.98:16816",
"172.200.4.40": "http://iprowq:yk2gbxo4@36.138.65.47:16818",
"172.200.5.215": "http://iprowq:yk2gbxo4@119.96.126.55:16817",
"172.200.4.43": "http://iprowq:yk2gbxo4@180.100.203.20:16816",
"172.200.4.31": "http://iprowq:yk2gbxo4@36.103.229.99:16816",
"172.200.4.252": "http://iprowq:yk2gbxo4@218.78.109.253:16816",
"172.200.4.23": "http://iprowq:yk2gbxo4@171.15.130.199:16816",
"172.200.4.26": "http://iprowq:yk2gbxo4@180.101.146.228:16816",
"172.200.4.214": "http://iprowq:yk2gbxo4@117.34.212.111:16816",
"172.200.4.39": "http://iprowq:yk2gbxo4@203.57.224.6:16816",
"172.20.1.94": "http://iprowq:yk2gbxo4@103.236.63.179:16816",
"172.20.1.67": "http://iprowq:yk2gbxo4@106.225.142.160:16816",
"172.20.1.68": "http://iprowq:yk2gbxo4@119.96.231.32:16816",
"172.20.1.76": "http://iprowq:yk2gbxo4@36.134.120.81:16816",
"172.20.1.77": "http://iprowq:yk2gbxo4@36.103.229.99:16816",
"172.20.1.78": "http://iprowq:yk2gbxo4@36.212.179.122:16816",
"172.20.1.20": "http://iprowq:yk2gbxo4@36.212.173.252:16816",
"172.20.1.19": "http://iprowq:yk2gbxo4@117.34.212.111:16816",
"172.20.1.21": "http://iprowq:yk2gbxo4@116.8.107.45:16816",
"172.20.1.23": "http://iprowq:yk2gbxo4@121.229.60.189:16816",
"172.20.1.29": "http://iprowq:yk2gbxo4@36.212.178.3:16816",
"172.20.1.22": "http://iprowq:yk2gbxo4@14.215.47.125:16816",
}
def _basic_auth(username: str, password: str) -> str:
token = base64.b64encode(f"{username}:{password}".encode()).decode()
return f"Basic {token}"
def _parse_proxy_url(proxy_url: str):
parsed = urlparse(proxy_url)
scheme = (parsed.scheme or "http").lower()
if scheme not in {"http", "https"}:
raise ValueError(f"unsupported upstream proxy scheme: {scheme}")
if not parsed.hostname or not parsed.port:
raise ValueError(f"invalid upstream proxy url: {proxy_url}")
auth = None
if parsed.username is not None:
auth = _basic_auth(parsed.username, parsed.password or "")
return scheme, parsed.hostname, parsed.port, auth
def _client_proxy_config(client_ip: str):
proxy_url = xhs_list_phone.get(client_ip)
if not proxy_url:
return None
return _parse_proxy_url(proxy_url)
def _client_ip(flow: mitmproxy.http.HTTPFlow) -> str:
return flow.client_conn.peername[0]
def _safe_text(message: mitmproxy.http.Message) -> str:
if not message.content:
return ""
try:
text = message.get_text(strict=False)
except Exception:
return f"<{len(message.content)} bytes binary>"
if len(text) > MAX_BODY_LEN:
return text[:MAX_BODY_LEN] + "\n...<truncated>"
return text
def _set_upstream_proxy(flow: mitmproxy.http.HTTPFlow):
client_ip = _client_ip(flow)
proxy_config = _client_proxy_config(client_ip)
if not proxy_config:
flow.metadata.pop("upstream_proxy", None)
return None
scheme, host, port, auth = proxy_config
desired_via = (scheme, (host, port))
current_via = flow.server_conn.via
already_open = flow.server_conn.timestamp_start is not None
if current_via != desired_via and already_open:
flow.server_conn = Server(
address=flow.server_conn.address,
transport_protocol=flow.server_conn.transport_protocol,
)
flow.server_conn.via = desired_via
flow.metadata["upstream_proxy"] = f"{scheme}://{host}:{port}"
return proxy_config
# ==================== MySQL 封装 ====================
class SimpleMySQL:
"""极简查询封装:只支持 SELECT * … WHERE ..."""
def __init__(self, charset="utf8mb4"):
self.cfg = dict(
host="tenant-2101894307-cn-beijing-public.bytehouse.volces.com",
port=3306,
user="bytehouse",
password="m1wUyPHX0H:JQDqesXaoc",
db="douchacha_data",
charset=charset,
cursorclass=pymysql.cursors.DictCursor,
autocommit=True,
)
self._conn = None
self._connect()
def _connect(self):
if self._conn:
self._conn.close()
self._conn = pymysql.connect(**self.cfg)
def _reconnect(self):
try:
self._connect()
except Exception as e:
raise RuntimeError(f"Reconnect failed: {e}") from e
def _execute(self, sql):
with self._conn.cursor() as cur:
cur.execute(sql)
return cur.fetchall()
def close(self):
self._conn.close()
def _ensure_conn(self):
try:
self._conn.ping(reconnect=True)
except Exception as e:
logger.error(f"MySQL ping failed, reconnecting: {e}")
self._conn = self._connect()
def replace_into(self, table, item_list):
self._ensure_conn()
if not item_list:
return 0
try:
keys = list(item_list[0].keys())
cols = ", ".join(f"`{k}`" for k in keys)
placeholders = ", ".join(["%s"] * len(keys))
sql = f"REPLACE INTO `{table}` ({cols}) VALUES ({placeholders})"
def sanitize_value(value):
if value is None:
return None
if isinstance(value, str):
return value.replace("`", "").replace("\\", "\\\\")
return value
values = [tuple(sanitize_value(item[k]) for k in keys) for item in item_list]
try:
self._conn.ping(reconnect=True)
with self._conn.cursor() as cur:
cur.executemany(sql, values)
logger.success(f"********** {table} 共写入{len(item_list)}条数据 **********")
return len(values)
except Exception as e:
logger.error(f"MySQL 执行错误: {e}")
raise
except Exception as e:
# print(f"Error: {e}")
self._connect()
def xxx(timestamp):
dt = datetime.datetime.fromtimestamp(timestamp)
return dt.strftime("%Y%m%d")
# ==================== 核心拦截 + 代理逻辑 ====================
class Counter:
def __init__(self):
self.db = SimpleMySQL()
self.ip_keyword_count = {}
self.ip_userId_count = {}
self.redis_conn = Redis(
host="172.16.0.24", password="aiyingli@@123", db=3, decode_responses=True
)
self.redis_conn2 = Redis(
host="172.16.0.24", password="aiyingli@@123", db=2, decode_responses=True
)
# ----- 上游代理 hook -----
def request(self, flow: mitmproxy.http.HTTPFlow) -> None:
data = {
"type": "request",
"client_ip": _client_ip(flow),
"method": flow.request.method,
"url": flow.request.pretty_url,
"headers": dict(flow.request.headers),
# "body": _safe_text(flow.request),
}
# ctx.log.info(json.dumps(data, ensure_ascii=False))
def requestheaders(self, flow: mitmproxy.http.HTTPFlow) -> None:
client_ip = _client_ip(flow)
proxy_config = _set_upstream_proxy(flow)
if proxy_config is None:
return
_, _, _, auth = proxy_config
if auth and flow.request.scheme == "http":
flow.request.headers["Proxy-Authorization"] = auth
# ctx.log.info(
# json.dumps(
# {
# "type": "upstream_selected",
# "client_ip": client_ip,
# "upstream": flow.metadata.get("upstream_proxy"),
# "target": f"{flow.request.host}:{flow.request.port}",
# },
# ensure_ascii=False,
# )
# )
def http_connect_upstream(self, flow: mitmproxy.http.HTTPFlow):
proxy_config = _set_upstream_proxy(flow)
if not proxy_config:
return
_, _, _, auth = proxy_config
if auth:
flow.request.headers["Proxy-Authorization"] = auth
# ----- 响应拦截 hook -----
def response(self, flow: mitmproxy.http.HTTPFlow) -> None:
data = {
"type": "response",
"client_ip": _client_ip(flow),
"status_code": flow.response.status_code,
"url": flow.request.pretty_url,
"headers": dict(flow.response.headers),
"body": _safe_text(flow.response),
}
# ctx.log.info(json.dumps(data, ensure_ascii=False))
if "v10/search/notes" in flow.request.url:
try:
client_ip = flow.client_conn.peername[0]
parsed_url = urlparse(flow.request.url)
query_params = parse_qs(parsed_url.query)
keyword = query_params.get("keyword", [""])[0]
if client_ip not in self.ip_keyword_count:
self.ip_keyword_count[client_ip] = {}
if keyword not in self.ip_keyword_count[client_ip]:
self.ip_keyword_count[client_ip][keyword] = 0
self.ip_keyword_count[client_ip][keyword] += 1
count = self.ip_keyword_count[client_ip][keyword]
logger.info(f"{client_ip} {keyword} 拦截次数:{count}")
self.redis_conn.hset(f"xhs_app:{client_ip}", keyword, count)
try:
if flow.response.json().get("data"):
items = flow.response.json().get("data", {}).get("items", [])
if len(items) > 0:
item_list = []
for idx, item in enumerate(items):
model_type = item.get("model_type")
if model_type in (
"dsl",
"hot_query",
"questionnaire_survey",
"ads",
"live",
):
continue
try:
global_rank = (count - 1) * 20 + idx + 1
data_dic = {}
data_dic["key_word"] = keyword
data_dic["rank"] = global_rank
data_dic["video_id"] = item.get("note").get("id")
data_dic["update_pt"] = xxx(time.time()) + "00"
data_dic["create_pt"] = xxx(time.time())
item_list.append(data_dic)
except:
# logger.success(f"{model_type} {item}")
pass
self.db.replace_into(
"ods_aidso_monitor_video_rank_xhs", item_list
)
logger.success(
f"{keyword} 拦截成功 len -> {len(items)}"
)
pass
else:
# logger.success(f"{keyword} 拦截失败")
pass
self.redis_conn.hset(
f"xhs_app:{client_ip}:{keyword}", keyword, "1"
)
else:
# print(flow.response.json())
if (
flow.response.json().get("msg")
== "访问次数已达上限,请改天再试"
):
self.redis_conn.hset(
f"xhs_app:status:{client_ip}", "status", "infinity"
)
# print(flow.response.json())
# if flow.response.json().get("code") == 300013:
# logger.error(flow.response.json())
# if flow.response.json().get("code") == -100:
# logger.error(flow.response.json())
# print("获取data失败咯")
except Exception:
# logger.error(f"解析 response 失败: {e}")
self.db = SimpleMySQL()
self.redis_conn.hset(
f"xhs_app:{client_ip}:{keyword}", keyword, "0"
)
if count >= 5:
del self.ip_keyword_count[client_ip][keyword]
logger.info(f"{client_ip} {keyword} 达到5次,已从 缓存 删除")
except Exception:
# logger.error(f" 失败: {e}")
pass
addons = [Counter()]
# 启动命令示例:
# mitmdump -q -s http_lanjie_keyword_proxy.py --listen-host 0.0.0.0 --listen-port 8901 --set confdir=./tools/.mitmproxy_simple --set block_global=false --set connection_strategy=lazy
\ No newline at end of file
import subprocess
import time
import signal
import sys
import os
from datetime import datetime, timedelta
from threading import Event, Thread
# ---------- 配置 ----------
MITMDUMP_BIN = "mitmdump"
RESTART_HOUR = 7
GRACEFUL_TIMEOUT = 10
COMMANDS = [
[MITMDUMP_BIN, "-s", "http_lanjie_keyword.py", "-q", "--listen-host", "0.0.0.0", "--set", "block_global=false"],
# [MITMDUMP_BIN, "-s", "http_lanjie_user.py", "-q", "--listen-host", "0.0.0.0", "--listen-port", "8081", "--set", "block_global=false"],
]
# 颜色(ANSI escape codes)
# 如果想改颜色,可把下面的值替换为其他 ANSI 颜色码
COLOR_RESET = "\x1b[0m"
STYLE_BOLD = "\x1b[1m"
# regular foreground colors
COLOR_RED = "\x1b[31m"
COLOR_GREEN = "\x1b[32m"
# bright variants
COLOR_BRIGHT_RED = "\x1b[91m"
COLOR_BRIGHT_GREEN = "\x1b[92m"
# 进程名 -> (stdout_color, stderr_color)
COLOR_MAP = {
"mitm_1": (COLOR_RED, STYLE_BOLD + COLOR_BRIGHT_RED),
"mitm_2": (COLOR_GREEN, STYLE_BOLD + COLOR_BRIGHT_GREEN),
}
# ---------- 配置结束 ----------
# Try to enable color on Windows if colorama is available
if os.name == "nt":
try:
import colorama
colorama.init()
except Exception:
pass
class MitmProcess:
def __init__(self, cmd, name):
self.cmd = cmd
self.name = name
self.proc = None
self.stdout_thread = None
self.stderr_thread = None
def start(self):
self.proc = subprocess.Popen(
self.cmd,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
bufsize=1,
# 1. 关键修改:不要使用 text=True,保持字节流
text=False,
preexec_fn=os.setpgrp if hasattr(os, "setpgrp") else None
)
print(f"[{datetime.now().isoformat()}] started {self.name} pid={self.proc.pid}")
# 2. 启动线程,无需改动
self.stdout_thread = Thread(target=self._stream_reader, args=(self.proc.stdout, False), daemon=True)
self.stderr_thread = Thread(target=self._stream_reader, args=(self.proc.stderr, True), daemon=True)
self.stdout_thread.start()
self.stderr_thread.start()
def _stream_reader(self, pipe, is_stderr: bool):
stdout_color, stderr_color = COLOR_MAP.get(self.name, (None, None))
prefix_label = f"[{self.name}][ERR]" if is_stderr else f"[{self.name}][OUT]"
color = stderr_color if is_stderr else stdout_color
try:
# 3. 关键修改:循环读取字节
for raw_line in iter(lambda: pipe.readline(), b""):
if not raw_line:
break
# 4. 关键修改:用 UTF-8 解码,并忽略错误
text = raw_line.decode('utf-8', errors='ignore').rstrip("\n")
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
if color:
sys.stdout.write(f"{color}{timestamp} {prefix_label}{COLOR_RESET} {text}\n")
else:
sys.stdout.write(f"{timestamp} {prefix_label} {text}\n")
sys.stdout.flush()
except Exception as e:
sys.stdout.write(f"[{self.name}] stream read error: {e}\n")
finally:
try:
pipe.close()
except Exception:
pass
def is_running(self):
return self.proc is not None and self.proc.poll() is None
def stop(self, graceful_timeout=GRACEFUL_TIMEOUT):
if not self.proc:
return
if self.is_running():
print(f"[{datetime.now().isoformat()}] stopping {self.name} pid={self.proc.pid} (SIGTERM)")
try:
os.killpg(os.getpgid(self.proc.pid), signal.SIGTERM)
except Exception:
try:
self.proc.terminate()
except Exception:
pass
try:
self.proc.wait(timeout=graceful_timeout)
print(f"[{datetime.now().isoformat()}] {self.name} exited with code {self.proc.returncode}")
except subprocess.TimeoutExpired:
print(f"[{datetime.now().isoformat()}] {self.name} did not exit in {graceful_timeout}s, sending SIGKILL")
try:
os.killpg(os.getpgid(self.proc.pid), signal.SIGKILL)
except Exception:
try:
self.proc.kill()
except Exception:
pass
self.proc.wait()
print(f"[{datetime.now().isoformat()}] {self.name} killed, returncode {self.proc.returncode}")
finally:
try:
if self.proc.stdout:
self.proc.stdout.close()
if self.proc.stderr:
self.proc.stderr.close()
except Exception:
pass
self.proc = None
def seconds_until_next_hour_minute(hour, minute=0):
now = datetime.now()
target = now.replace(hour=hour, minute=minute, second=0, microsecond=0)
if target <= now:
target += timedelta(days=1)
return (target - now).total_seconds()
def restart_loop(processes, stop_event: Event):
while not stop_event.is_set():
secs = seconds_until_next_hour_minute(RESTART_HOUR, 0)
dt = datetime.now() + timedelta(seconds=secs)
print(f"[{datetime.now().isoformat()}] Next scheduled restart at {dt.strftime('%Y-%m-%d %H:%M:%S')} (in {int(secs)}s).")
if stop_event.wait(timeout=secs):
break
print(f"[{datetime.now().isoformat()}] Performing scheduled restart...")
for p in processes:
try:
p.stop()
except Exception as e:
print(f"Error stopping {p.name}: {e}")
for p in processes:
try:
p.start()
except Exception as e:
print(f"Error starting {p.name}: {e}")
print(f"[{datetime.now().isoformat()}] Scheduled restart complete.")
def monitor_loop(processes, stop_event: Event, check_interval=10):
while not stop_event.is_set():
for p in processes:
if not p.is_running():
print(f"[{datetime.now().isoformat()}] detected {p.name} not running; restarting...")
try:
p.start()
except Exception as e:
print(f" failed to restart {p.name}: {e}")
stop_event.wait(timeout=check_interval)
def main():
processes = []
for idx, cmd in enumerate(COMMANDS, start=1):
name = f"mitm_{idx}"
processes.append(MitmProcess(cmd, name))
for p in processes:
try:
p.start()
except Exception as e:
print(f"Failed to start {p.name}: {e}")
stop_event = Event()
t_restart = Thread(target=restart_loop, args=(processes, stop_event), daemon=True)
t_monitor = Thread(target=monitor_loop, args=(processes, stop_event), daemon=True)
t_restart.start()
t_monitor.start()
def handle_signal(signum, frame):
print(f"[{datetime.now().isoformat()}] got signal {signum}, shutting down...")
stop_event.set()
for p in processes:
try:
p.stop()
except Exception as e:
print(f"Error stopping {p.name}: {e}")
sys.exit(0)
signal.signal(signal.SIGINT, handle_signal)
signal.signal(signal.SIGTERM, handle_signal)
try:
while True:
time.sleep(3600)
except KeyboardInterrupt:
handle_signal(signal.SIGINT, None)
if __name__ == "__main__":
main()
\ No newline at end of file
import asyncio
import base64
import datetime
import time
from concurrent.futures import ThreadPoolExecutor
import mitmproxy.http
from mitmproxy import ctx
from loguru import logger
from urllib.parse import urlparse, parse_qs
from redis import Redis
import pymysql
from pymysql.err import OperationalError
from tools import client_account,search_clientip,user_clientip,client_proxy
from mitmproxy.net.server_spec import ServerSpec
from mitmproxy.connection import Server
MAX_USER_FETCH_COUNT = 10
REDIS_TIMEOUTS = dict(socket_connect_timeout=3, socket_timeout=3, health_check_interval=30)
# ==================== 按手机分配上游出口 IP ====================
# key 是手机在局域网中的 IP,value 是该手机独享的上游代理。
# 未配置的手机保持直连。
XHS_USER_PHONE_PROXIES = {
"172.20.1.253": "http://iprowq:yk2gbxo4@36.138.65.47:16816",
"172.20.1.254": "http://iprowq:yk2gbxo4@36.137.200.157:16816",
}
def _basic_auth(username: str, password: str) -> str:
token = base64.b64encode(f"{username}:{password}".encode()).decode()
return f"Basic {token}"
def _parse_proxy_url(proxy_url: str):
parsed = urlparse(proxy_url)
scheme = (parsed.scheme or "http").lower()
if scheme not in {"http", "https"}:
raise ValueError(f"unsupported upstream proxy scheme: {scheme}")
if not parsed.hostname or not parsed.port:
raise ValueError(f"invalid upstream proxy url: {proxy_url}")
auth = None
if parsed.username is not None:
auth = _basic_auth(parsed.username, parsed.password or "")
return scheme, parsed.hostname, parsed.port, auth
def _client_ip(flow: mitmproxy.http.HTTPFlow) -> str:
peername = getattr(flow.client_conn, "peername", None)
return peername[0] if peername else "unknown"
def _client_proxy_config(client_ip: str):
proxy_url = XHS_USER_PHONE_PROXIES.get(client_ip)
if not proxy_url:
return None
return _parse_proxy_url(proxy_url)
def _set_upstream_proxy(flow: mitmproxy.http.HTTPFlow):
client_ip = _client_ip(flow)
proxy_config = _client_proxy_config(client_ip)
if not proxy_config:
flow.metadata.pop("upstream_proxy", None)
return None
scheme, host, port, auth = proxy_config
desired_via = (scheme, (host, port))
current_via = flow.server_conn.via
already_open = flow.server_conn.timestamp_start is not None
# 同一客户端连接内如果上游发生变化,创建新的 server connection,
# 防止复用到另一台手机的出口代理。
if current_via != desired_via and already_open:
flow.server_conn = Server(
address=flow.server_conn.address,
transport_protocol=flow.server_conn.transport_protocol,
)
flow.server_conn.via = desired_via
flow.metadata["upstream_proxy"] = f"{scheme}://{host}:{port}"
return proxy_config
class SimpleMySQL:
"""极简查询封装:只支持 SELECT * … WHERE ..."""
def __init__(self, charset="utf8mb4"):
self.cfg = dict(host="tenant-2101894307-cn-beijing-public.bytehouse.volces.com", port=3306, user="bytehouse",
password="m1wUyPHX0H:JQDqesXaoc", db="douchacha_data", charset=charset,
cursorclass=pymysql.cursors.DictCursor,
autocommit=True, connect_timeout=5, read_timeout=10, write_timeout=10)
self._conn = None
def _connect(self):
if self._conn:
self._conn.close()
self._conn = pymysql.connect(**self.cfg)
def _reconnect(self):
try:
self._connect()
except Exception as e:
raise RuntimeError(f"Reconnect failed: {e}") from e
def _execute(self, sql):
with self._conn.cursor() as cur:
cur.execute(sql)
return cur.fetchall()
def close(self):
if self._conn is not None:
self._conn.close()
self._conn = None
def _ensure_conn(self):
if self._conn is None:
self._connect()
return
try:
self._conn.ping(reconnect=True) # 如果断了会自动重连
except Exception as e:
logger.error(f"MySQL ping failed, reconnecting: {e}")
self._connect()
def replace_into(self, table, item_list):
self._ensure_conn()
if not item_list:
return 0
try:
keys = list(item_list[0].keys())
cols = ", ".join(f"`{k}`" for k in keys)
placeholders = ", ".join(["%s"] * len(keys))
sql = f"REPLACE INTO `{table}` ({cols}) VALUES ({placeholders})"
# 处理特殊字符
def sanitize_value(value):
if value is None:
return None
if isinstance(value, str):
# 移除或转义可能引起问题的字符
return value.replace('`', '').replace('\\', '\\\\')
return value
values = [tuple(sanitize_value(item[k]) for k in keys) for item in item_list]
try:
# 🔑 关键:写之前先 ping 一下,断了就重连
self._conn.ping(reconnect=True)
with self._conn.cursor() as cur:
cur.executemany(sql, values)
# self._conn.commit()
logger.success(f"********** {table} 共写入{len(item_list)}条数据 **********")
return len(values)
except Exception as e:
logger.error(f"MySQL 执行错误: {e}")
raise
except Exception as e:
logger.error(f"MySQL 写入失败 table={table}: {e}")
raise
def xxx(timestamp):
dt = datetime.datetime.fromtimestamp(timestamp)
# 格式化为年月日
return dt.strftime("%Y%m%d")
class Counter:
def __init__(self):
# 用来记录每个客户端 IP 的请求次数
self.db = SimpleMySQL()
self.ip_keyword_count = {}
self.ip_userId_count = {}
self.redis_conn = Redis(host="172.16.0.24", password="aiyingli@@123", db=3, decode_responses=True, **REDIS_TIMEOUTS)
self.redis_conn2 = Redis(host="172.16.0.24", password="aiyingli@@123", db=2, decode_responses=True, **REDIS_TIMEOUTS)
self.logged_proxy_clients = set()
# 单线程串行访问 MySQL 连接和采集计数,避免阻塞代理事件循环。
self._response_executor = ThreadPoolExecutor(max_workers=1, thread_name_prefix="xhs-user-storage")
def running(self):
ctx.options.update(connection_strategy="lazy")
def _close_storage(self):
for backend in (self.db, self.redis_conn, self.redis_conn2):
try:
backend.close()
except Exception as e:
logger.warning(f"关闭采集存储连接失败: {e}")
def done(self):
# 关闭动作排在已经提交的采集任务之后,避免跨线程关闭正在写入的连接。
self._response_executor.submit(self._close_storage)
self._response_executor.shutdown(wait=False)
def requestheaders(self, flow: mitmproxy.http.HTTPFlow) -> None:
client_ip = _client_ip(flow)
proxy_config = _set_upstream_proxy(flow)
if proxy_config is None:
return
_, _, _, auth = proxy_config
if auth and flow.request.scheme == "http":
flow.request.headers["Proxy-Authorization"] = auth
if client_ip not in self.logged_proxy_clients:
logger.info(
f"手机 {client_ip} 使用独立上游代理 "
f"{flow.metadata.get('upstream_proxy')}"
)
self.logged_proxy_clients.add(client_ip)
def http_connect_upstream(self, flow: mitmproxy.http.HTTPFlow) -> None:
proxy_config = _set_upstream_proxy(flow)
if not proxy_config:
return
_, _, _, auth = proxy_config
if auth:
flow.request.headers["Proxy-Authorization"] = auth
async def response(self, flow: mitmproxy.http.HTTPFlow):
if flow.response is None or "api/sns/v4/note/user/posted" not in flow.request.url:
return
started = time.monotonic()
try:
await asyncio.get_running_loop().run_in_executor(
self._response_executor, self._process_response, flow
)
finally:
elapsed = time.monotonic() - started
if elapsed >= 3:
logger.warning(
f"采集存储处理缓慢 client={_client_ip(flow)} elapsed={elapsed:.1f}s "
"(含排队时间),请检查 MySQL/Redis"
)
def _process_response(self, flow: mitmproxy.http.HTTPFlow):
if "api/sns/v4/note/user/posted" in flow.request.url:
try:
client_ip = _client_ip(flow)
# print(client_ip,flow.response.json())
# 获取 URL 中的 user_id 参数
parsed_url = urlparse(flow.request.url)
query_params = parse_qs(parsed_url.query)
user_id = query_params.get("user_id", [""])[0]
count = 0
if user_id not in self.ip_userId_count:
self.ip_userId_count[user_id] = 0
self.redis_conn2.hset(f"xhs_app:{client_ip}", user_id, '0')
# logger.success(f"初始化keyword:{user_id} 结果 -> {self.ip_userId_count}")
try:
if flow.response.json().get("data"):
data = flow.response.json().get("data")
notes = data.get("notes")
posted_dic_list = []
posted_dic_list_v2 = []
for note in notes:
# logger.success(f"note -> {note}")
posted_dic = {}
posted_dic["user_id"] = note.get('user').get("userid")
posted_dic["video_id"] = note.get('id')
posted_dic["insert_time"] = int(time.time())
posted_dic["user_nick_name"] = note.get('user').get("nickname")
# posted_dic["type"] = note.get('type')
posted_dic["video_desc"] = note.get('title') + note.get('desc')
# posted_dic["title"] = note.get('title')
# posted_dic["last_update_time"] = note.get('last_update_time')
posted_dic["comment_count"] = note.get('comments_count')
posted_dic["video_score"] = 0
posted_dic["forward_count"] = 0
posted_dic["download_count"] = 0
posted_dic["share_url"] = ""
posted_dic["tag_id_1"] = ""
posted_dic["tag_name_1"] = ""
posted_dic["tag_id_2"] = ""
posted_dic["tag_name_2"] = ""
posted_dic["tag_id_3"] = ""
posted_dic["tag_name_3"] = ""
posted_dic["share_count"] = note.get('share_count')
posted_dic["collect_count"] = note.get('collected_count')
posted_dic["create_time"] = note.get('create_time')
posted_dic["good_count"] = note.get('likes')
for i in note.get("images_list"):
if i.get("url") != "":
cover = i.get("url")
if note.get('type') == "normal":
# posted_dic["video_url"] = ""
posted_dic["duration"] = 0
else:
stream = note.get("video_info_v2").get("media").get("stream")
# video_url = ''
for k, v in stream.items():
if len(v) > 0:
backup_urls = v[0].get("backup_urls")
if len(backup_urls) > 0:
video_url = backup_urls[0]
duration = v[0].get("duration")
# posted_dic["video_url"] = video_url
posted_dic["duration"] = duration
posted_dic["pt"] = xxx(note.get('create_time'))
posted_dic["cover"] = cover
posted_dic_list.append(posted_dic)
posted_dic_v2 = posted_dic.copy()
posted_dic_v2["video_id_tag"] = posted_dic["video_id"]
posted_dic_v2["video_id"] = f'{posted_dic["user_id"]}{posted_dic["create_time"]}'
posted_dic_list_v2.append(posted_dic_v2)
self.db.replace_into("ods_aidso_monitor_video_xhs",posted_dic_list)
self.db.replace_into("ods_aidso_monitor_video_xhs_v2", posted_dic_list_v2)
has_more = data.get("has_more")
if has_more:
self.ip_userId_count[user_id] += 1
count = self.ip_userId_count[user_id]
self.redis_conn2.hset(f"xhs_app:{client_ip}", user_id, count)
logger.info(f"{client_ip} {user_id} 拦截次数:{count}")
else:
logger.success("当前无更多视频")
self.redis_conn2.hset(
f"xhs_app:{client_ip}", user_id, str(MAX_USER_FETCH_COUNT)
)
del self.ip_userId_count[user_id]
if count == MAX_USER_FETCH_COUNT:
del self.ip_userId_count[user_id]
logger.info(
f"{user_id} 达到{MAX_USER_FETCH_COUNT}次,已从缓存删除"
)
except Exception:
logger.exception(f"解析或保存视频列表出错 client={client_ip} user_id={user_id}")
except Exception:
logger.exception(f"达人响应处理失败 client={_client_ip(flow)}")
def error(self, flow: mitmproxy.http.HTTPFlow) -> None:
if flow.error:
logger.warning(
f"请求失败 client={_client_ip(flow)} upstream={flow.metadata.get('upstream_proxy', '直连')} "
f"host={flow.request.host} path={urlparse(flow.request.url).path} error={flow.error}"
)
addons = [
Counter()
]
# 启动时不要再传全局 --mode upstream,否则会覆盖/干扰按手机分配逻辑。
# mitmdump -s http_lanjie_user.py -q --listen-host 0.0.0.0 --listen-port 8081 --set block_global=false --set connection_strategy=lazy
# mitmdump -p 8081 -s http_lanjie_user.py -q --listen-host 0.0.0.0 --set block_global=false --mode upstream:http://119.96.231.32:16816 --upstream-auth iprowq:yk2gbxo4
# mitmdump -p 8901 -s http_lanjie_keyword_proxy.py -q --listen-host 0.0.0.0 --set block_global=false --mode upstream:http://36.134.120.165:16817 --upstream-auth iprowq:yk2gbxo4
import base64
import datetime
import time
import mitmproxy.http
from mitmproxy import ctx
from loguru import logger
from urllib.parse import urlparse, parse_qs
from redis import Redis
import pymysql
from pymysql.err import OperationalError
from tools import client_account,search_clientip,user_clientip,client_proxy
from mitmproxy.net.server_spec import ServerSpec
from mitmproxy.connection import Server
class SimpleMySQL:
"""极简查询封装:只支持 SELECT * … WHERE ..."""
def __init__(self, charset="utf8mb4"):
self.cfg = dict(host="tenant-2101894307-cn-beijing-public.bytehouse.volces.com", port=3306, user="bytehouse",
password="m1wUyPHX0H:JQDqesXaoc", db="douchacha_data", charset=charset,
cursorclass=pymysql.cursors.DictCursor,
autocommit=True)
self._conn = None
self._connect()
def _connect(self):
if self._conn:
self._conn.close()
self._conn = pymysql.connect(**self.cfg)
def _reconnect(self):
try:
self._connect()
except Exception as e:
raise RuntimeError(f"Reconnect failed: {e}") from e
def _execute(self, sql):
with self._conn.cursor() as cur:
cur.execute(sql)
return cur.fetchall()
def close(self):
self._conn.close()
def _ensure_conn(self):
try:
self._conn.ping(reconnect=True) # 如果断了会自动重连
except Exception as e:
logger.error(f"MySQL ping failed, reconnecting: {e}")
self._conn = self._connect() # 你自己封装的重连逻辑
def replace_into(self, table, item_list):
self._ensure_conn()
if not item_list:
return 0
try:
keys = list(item_list[0].keys())
cols = ", ".join(f"`{k}`" for k in keys)
placeholders = ", ".join(["%s"] * len(keys))
sql = f"REPLACE INTO `{table}` ({cols}) VALUES ({placeholders})"
# 处理特殊字符
def sanitize_value(value):
if value is None:
return None
if isinstance(value, str):
# 移除或转义可能引起问题的字符
return value.replace('`', '').replace('\\', '\\\\')
return value
values = [tuple(sanitize_value(item[k]) for k in keys) for item in item_list]
try:
# 🔑 关键:写之前先 ping 一下,断了就重连
self._conn.ping(reconnect=True)
with self._conn.cursor() as cur:
cur.executemany(sql, values)
# self._conn.commit()
logger.success(f"********** {table} 共写入{len(item_list)}条数据 **********")
return len(values)
except Exception as e:
logger.error(f"MySQL 执行错误: {e}")
raise
except Exception as e:
print(f"Error: {e}")
self._connect()
def xxx(timestamp):
dt = datetime.datetime.fromtimestamp(timestamp)
# 格式化为年月日
return dt.strftime("%Y%m%d")
class Counter:
def __init__(self):
# 用来记录每个客户端 IP 的请求次数
self.db = SimpleMySQL()
self.ip_keyword_count = {}
self.ip_userId_count = {}
self.redis_conn = Redis(host="172.16.0.24", password="aiyingli@@123", db=3, decode_responses=True)
self.redis_conn2 = Redis(host="172.16.0.24", password="aiyingli@@123", db=2, decode_responses=True)
def response(self, flow: mitmproxy.http.HTTPFlow):
if "api/sns/v4/note/user/posted" in flow.request.url:
try:
client_ip = flow.client_conn.peername[0]
# print(client_ip,flow.response.json())
# 获取 URL 中的 user_id 参数
parsed_url = urlparse(flow.request.url)
query_params = parse_qs(parsed_url.query)
user_id = query_params.get("user_id", [""])[0]
count = 0
if user_id not in self.ip_userId_count:
self.ip_userId_count[user_id] = 0
self.redis_conn2.hset(f"xhs_app:{client_ip}", user_id, '0')
# logger.success(f"初始化keyword:{user_id} 结果 -> {self.ip_userId_count}")
try:
if flow.response.json().get("data"):
data = flow.response.json().get("data")
notes = data.get("notes")
posted_dic_list = []
for note in notes:
# logger.success(f"note -> {note}")
posted_dic = {}
posted_dic["user_id"] = note.get('user').get("userid")
posted_dic["video_id"] = note.get('id')
posted_dic["user_nick_name"] = note.get('user').get("nickname")
# posted_dic["type"] = note.get('type')
posted_dic["video_desc"] = note.get('title') + note.get('desc')
# posted_dic["title"] = note.get('title')
# posted_dic["last_update_time"] = note.get('last_update_time')
posted_dic["comment_count"] = note.get('comments_count')
posted_dic["video_score"] = 0
posted_dic["forward_count"] = 0
posted_dic["download_count"] = 0
posted_dic["share_url"] = ""
posted_dic["tag_id_1"] = ""
posted_dic["tag_name_1"] = ""
posted_dic["tag_id_2"] = ""
posted_dic["tag_name_2"] = ""
posted_dic["tag_id_3"] = ""
posted_dic["tag_name_3"] = ""
posted_dic["share_count"] = note.get('share_count')
posted_dic["collect_count"] = note.get('collected_count')
posted_dic["create_time"] = note.get('create_time')
posted_dic["good_count"] = note.get('likes')
for i in note.get("images_list"):
if i.get("url") != "":
cover = i.get("url")
if note.get('type') == "normal":
# posted_dic["video_url"] = ""
posted_dic["duration"] = 0
else:
stream = note.get("video_info_v2").get("media").get("stream")
# video_url = ''
for k, v in stream.items():
if len(v) > 0:
backup_urls = v[0].get("backup_urls")
if len(backup_urls) > 0:
video_url = backup_urls[0]
duration = v[0].get("duration")
# posted_dic["video_url"] = video_url
posted_dic["duration"] = duration
posted_dic["pt"] = xxx(note.get('create_time'))
posted_dic["cover"] = cover
posted_dic_list.append(posted_dic)
self.db.replace_into("ods_aidso_monitor_video_xhs_v2",posted_dic_list)
has_more = data.get("has_more")
if has_more:
self.ip_userId_count[user_id] += 1
count = self.ip_userId_count[user_id]
self.redis_conn2.hset(f"xhs_app:{client_ip}", user_id, count)
logger.info(f"{client_ip} {user_id} 拦截次数:{count}")
else:
logger.success("当前无更多视频")
self.redis_conn2.hset(f"xhs_app:{client_ip}", user_id, '15')
del self.ip_userId_count[user_id]
if count == 15:
del self.ip_userId_count[user_id]
logger.info(f"{user_id} 达到15次,已从 缓存 删除")
except Exception as e:
logger.error(f"解析视频列表出错 {e}")
except Exception as e:
logger.error(e)
addons = [
Counter()
]
# mitmdump -s http_lanjie_user.py -q --listen-host 0.0.0.0 --listen-port 8081 --set block_global=false
# mitmdump -p 8081 -s http_lanjie_user.py -q --listen-host 0.0.0.0 --set block_global=false --mode upstream:http://119.96.231.32:16816 --upstream-auth iprowq:yk2gbxo4
# mitmdump -p 8901 -s http_lanjie_keyword.py -q --listen-host 0.0.0.0 --set block_global=false --mode upstream:http://36.134.120.165:16817 --upstream-auth iprowq:yk2gbxo4
\ No newline at end of file
import sys
import os
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from tools.common_func import feishu_alert
import asyncio
import json
import random
import re
import base64
import time
import requests
from playwright.async_api import async_playwright
from tools.common import common_redis4
from loguru import logger
from tools.mysqlConnect import MYSQL_CONNECT
from tools.utils import deepseek_online_phone_proxy_dict, deepseek_phone_proxy_dict
login_flag = False
token_future = None # 新增:让 handle_response 能把 token 传回 login()
mysql_connect = MYSQL_CONNECT()
def json_from_jsonp(s: str):
# 去掉常见 XSSI 前缀
s = s.lstrip(")]}',\n\r\t ")
# 1) 先试正则:funcName ( { ... } ) [;]
m = re.search(r'^[\w$]+\s*\(\s*(\{.*\})\s*\)\s*;?\s*$', s, re.S)
if m:
return json.loads(m.group(1))
# 2) 回退方案:截取第一个 '{' 到最后一个 '}'
i, j = s.find('{'), s.rfind('}')
if i != -1 and j != -1 and j > i:
return json.loads(s[i:j + 1])
raise ValueError("Not a valid JSON or JSONP string")
def recv_msg(phone):
code = ""
start_time = int(time.time())
deadline = start_time + 60
while time.time() < deadline:
rows = mysql_connect.select_sql(f"SELECT * FROM recv_sms WHERE phone_num = {phone} AND recv_time >= {start_time} AND recv_time <= {deadline}")
if rows:
msg = rows[0][1]
code = re.search(r"\b(\d{4,6})\b", msg).group(1)
return code
time.sleep(3)
return code
async def handle_response(response, page, context, phone):
global login_flag, token_future # 新增:确保能改到外部变量
if "ca/v1/registe" in response.url:
await asyncio.sleep(3)
resp_text = await response.text()
data_json = json_from_jsonp(resp_text)
bg_url_path = data_json.get("detail").get("bg")
domains = data_json.get("detail").get("domains")
order = data_json.get("detail").get("order")
bg_url = "http://" + domains[random.randint(0, len(domains) - 1)] + bg_url_path
r = requests.get(bg_url)
data = {
"token": "gHhbPwEYjRnAZ1pA8epncxuiz02t2nKsWtPrNKUiBmA", # 输入自己的token
"type": "107901",
"image": base64.b64encode(r.content).decode(), # 待识别图的base64
"extra": order[0], # 原网站上那句话,比如,点击图中最小的红色六棱柱
}
r2 = requests.post("http://api.jfbym.com/api/YmServer/customApi", data=data).json()
print(r2)
value = r2.get("data").get("data")
pt_x, pt_y = value.split(",")
NAT_W, NAT_H = 600, 300
target = None
for fr in page.frames:
cand = fr.locator("img.shumei_captcha_loaded_img_bg")
if await cand.count():
target = cand.first
break
if not target:
raise RuntimeError("找不到图片(主文档和所有 iframe 都查过)")
# 3) 取显示尺寸并做比例映射
bb = await target.bounding_box()
if not bb:
raise RuntimeError("bounding_box() 为空")
w = float(bb["width"])
h = float(bb["height"])
x = float(pt_x) * (w / float(NAT_W))
y = float(pt_y) * (h / float(NAT_H))
# 2) 等可见 & 滚动到视口
await target.wait_for(state="visible", timeout=10_000)
await target.scroll_into_view_if_needed()
await target.click(position={"x": int(x), "y": int(y)})
elif "ca/v2/fverify" in response.url:
resp_text = await response.text()
data_json = json_from_jsonp(resp_text)
if data_json.get("message") == "success":
logger.success("验证码通过成功!!!开始查询当前验证码")
for i in range(1,4):
code = recv_msg(phone)
if not code:
await asyncio.sleep(2)
await page.locator('//*[@id="root"]/div/div/div[2]/div/div/div[2]/div[1]/div[4]/div[1]/div/div[2]').click()
continue
break
if not code:
msg = f"[deepseek] {phone} 未获取到验证码 该账号停止登陆 手动测试后解封"
logger.error(msg)
feishu_alert(msg)
common_redis4.hset("ai:deepseek:account:status", phone,"1")
return
logger.success(f"{phone} 获取验证码为:{code}")
await asyncio.sleep(5)
await page.locator('//*[@id="root"]/div/div/div[2]/div/div/div[2]/div[1]/div[4]/div[1]/div/div[1]/input').type(code,delay=100)
await asyncio.sleep(3)
await page.locator('//*[@id="root"]/div/div/div[2]/div/div/div[2]/div[1]/div[6]').click()
elif "api/v0/users/login_by_mobile_sms" in response.url:
data = await response.json()
if data.get("data").get("biz_msg") == "SMS_VERIFY_FAILED":
logger.error("登陆失败")
elif data.get("data").get("biz_msg") == "LOGIN_TO_EXISTING_ACCOUNT" or data.get("data").get("biz_msg") == "":
logger.success("登陆成功")
token = data.get("data").get("biz_data").get("user").get("token")
client_version = ""
headers = await response.request.headers_array()
for h in await response.request.headers_array():
if h['name'].lower() == "x-client-version":
client_version = h['value']
if token:
login_flag = True
token_info = {
"token":token,
'client_version':client_version
}
if token and token_future and not token_future.done():
token_future.set_result(token_info)
else:
logger.error(f"当前待处理 {data}")
async def launch_browser(proxy):
playwright = await async_playwright().start()
context = await playwright.chromium.launch(
headless=False,
args=[
"--window-size=800,600",
# "--start-maximized"
"--disable-gpu",
],
proxy={
"server": proxy,
"username": "iprowq",
"password": "yk2gbxo4",
}
)
page = await context.new_page()
page.set_default_timeout(1000000)
await page.add_init_script("""
Object.defineProperty(navigator, 'webdriver', {
get: () => undefined
});
window.navigator.chrome = { runtime: {} };
""")
await asyncio.sleep(1) # 等待 profile 锁释放
return playwright, context, page
async def login(phone,proxy):
playwright, context, page = await launch_browser(proxy)
global token_future
loop = asyncio.get_running_loop()
token_future = loop.create_future()
page.on("response", lambda response: asyncio.create_task(
handle_response(response, page, context, phone)
))
try:
url = "https://chat.deepseek.com/sign_in"
await page.goto(url)
await page.wait_for_selector("#root > div > div > div._99ad066 > div > div > div.ds-sign-up-form__main > div.ds-sign-up-form__main-hero > div:nth-child(3) > div.ds-form-item__content > div > input", state="attached", timeout=5000)
await page.locator('//*[@id="root"]/div/div/div[2]/div/div/div[2]/div[1]/div[3]/div[1]/div/input').fill(phone)
await asyncio.sleep(1)
await page.locator('//*[@id="root"]/div/div/div[2]/div/div/div[2]/div[1]/div[4]/div[1]/div/div[2]').click()
await asyncio.sleep(10)
try:
token_info = await asyncio.wait_for(token_future, timeout=120) # 可调
except asyncio.TimeoutError:
logger.error("等待 token 超时")
return
token = None
if token_info.get("token"):
await asyncio.sleep(5) # 让站点把 cookie/本地状态写全
cookies = await page.context.cookies()
token = token_info.get("token")
client_version = token_info.get("client_version")
cookie_header_all = "; ".join(f"{c['name']}={c['value']}" for c in cookies)
redis_status_key = 'ai:deepseek:cookies:status'
redis_cookie_key = 'ai:deepseek:cookies:cookie'
value = {"authorization": token, "cookie": cookie_header_all,"client_version":client_version}
logger.success(value)
common_redis4.hset(redis_status_key,phone,"1")
common_redis4.hset(redis_cookie_key,phone,json.dumps(value))
logger.success(f"{phone} 设置redis key完成")
await page.close()
await context.close()
return
else:
logger.error("获取token失败")
except Exception as e:
logger.error(e)
pass
async def main():
while 1:
for phone,proxy in deepseek_phone_proxy_dict.items():
status = common_redis4.hget("ai:deepseek:cookies:status", phone)
if status == "1":
continue
else:
status = common_redis4.hget("ai:deepseek:account:status",phone)
if status == "1":
continue
logger.error(f"{phone} 账号异常 重新登录")
await login(phone,proxy)
await asyncio.sleep(3)
# await login("177102t81562")
if __name__ == '__main__':
asyncio.run(main())
-----BEGIN CERTIFICATE-----
MIIDNTCCAh2gAwIBAgIUB4W0ull6dSleyD9ho9ToZzIoNEAwDQYJKoZIhvcNAQEL
BQAwKDESMBAGA1UEAwwJbWl0bXByb3h5MRIwEAYDVQQKDAltaXRtcHJveHkwHhcN
MjYwNTA0MTc1NjIzWhcNMzYwNTAzMTc1NjIzWjAoMRIwEAYDVQQDDAltaXRtcHJv
eHkxEjAQBgNVBAoMCW1pdG1wcm94eTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCC
AQoCggEBAL6zCRtG8y/CnwUJXTL4mh93uoklDifFEypITCsnk6baHzQPN3eW9TPc
vt8U+1K/q3d6HeIY3zV0S5aEkB2iyXA6i8JjOA/UYYAL6kO2p+9h2nvD/nKyjm6T
nIDEP+/t4QVtS0ejfgho/ASLMk+0B/cwz8DIXGqRorZCxR1A0jbkM2KFGh5xoUlf
q/2eCHEVZB6wI51rpHeNQRtlo/dXH6W1eEifsR+QaRSv0V3A0/q3t8QxyL1pBk1G
8kOAOk5JPJsvfTMDfuXwYTrh+nuynahSp8WRS0YNDPgqAuvDdx92f6xsW572Qd6L
yixbLsd6fxyoIj/OZm3EB+BJeEUJf0ECAwEAAaNXMFUwDwYDVR0TAQH/BAUwAwEB
/zATBgNVHSUEDDAKBggrBgEFBQcDATAOBgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYE
FJ691AbhEI4DSoPI1HZzdCiEJOfNMA0GCSqGSIb3DQEBCwUAA4IBAQCNBELVzv6+
YlrS+yWQvoTp49/4tCIFkOdYTOOttGYNumAjnMFbeLbJtq0exR0TpHqCjeH8G3cs
ay9NpobhAlsS5CLmwwXCnHyCHGHJrrLjGpKbFNBtj5j8FQoqoPNSNDq8dZ3dlzM/
aJX4TP0RbSfz0qhLiHKdGfEi3rRmZ+1Fo8HeYmo14W1VuLEJ0H0Zzq2IYj5fw75E
g2uj1Q/9GzIDzqL/QX2hNUY1fvez1/a+lVJr0CcQUHARwdrvk4vFsHqgY1adyOoF
H1GUL/NzlAO6COyrMeuOfFB3FzBQNanq40FPCfBP86dxYeptUHt2/6gUU5CkbowD
rdePcUaopnen
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
MIIDNTCCAh2gAwIBAgIUJXqISF+lVWr2Ne/9WFFMOfLj6vwwDQYJKoZIhvcNAQEL
BQAwKDESMBAGA1UEAwwJbWl0bXByb3h5MRIwEAYDVQQKDAltaXRtcHJveHkwHhcN
MjYwNDA4MTE1NzMyWhcNMzYwNDA3MTE1NzMyWjAoMRIwEAYDVQQDDAltaXRtcHJv
eHkxEjAQBgNVBAoMCW1pdG1wcm94eTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCC
AQoCggEBAOytsXKKV1aljzqvm9ryqY/OfTg66zvDUl80Eg+AVNB0AFaoAbaGLGfe
opvw2JWZKnoH/tCb0FUB+6DJAcbr0ineLmIjhdoWB8jUbbQ/QywuIqJwt2nVLHh5
EvQJRhn5FbNT4rugH9juah+R1BPfeZesCUzd+tuKx1bQfbBsAkiTUAnwRYsI0p8D
Mv9p8cpYk+rn1a4zbTZ9r39/vW5+Rl2oC+e12WRMCDsn4wpamh0TUqCNgPsZDOcq
+BfbL8AxoPx7EQa8B/Tho+mkDnSRPC8uNpIS8t+btEKqYk27UxaD/9DFdgIrBLgR
goyFm+56duVlyDNRMGxJJyjJ5wOYtUkCAwEAAaNXMFUwDwYDVR0TAQH/BAUwAwEB
/zATBgNVHSUEDDAKBggrBgEFBQcDATAOBgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYE
FNfD3rmr9yzbrAK7nMm8sNgg3TV3MA0GCSqGSIb3DQEBCwUAA4IBAQDLsUUL4Q+5
43XBYphEVfN3etJl8m/TVurvPimu/XDPXnzkdawIYrJtrOjfi9LS97tu6ShxNvJQ
YlCn45lpq3VFD90STWcRheslqyBnQ4XnvCRjM5OC+URzc130YMExXSWvvXOR8Vt0
Y0DHmNkwyz7gbKAycswWu96VkOZHxSRCzIi8IkbE0L+zoKpvh7VhMcLZKmFngdmR
Lp7gghBu3YG9wveNOv5lPrIOuajvitX2TSgAZ2jDlUflUoJ8RjCcW/VB+G+9DNOJ
Vq1a77SToVkWVRlwG5uoQGhBHJospd48zPrsrqYJj8EdkPuseuN/Trs41TxM9hF1
QOCPMZ9phhWY
-----END CERTIFICATE-----
import subprocess
search_clientip = [
"172.200.2.179",
"172.200.2.119",
"172.200.2.109",
# "172.200.2.210",
# "172.200.2.118",
# "172.200.2.74",
# "172.200.2.132",
# "172.200.2.83",
# "172.200.2.75",
# "172.200.2.126",
# "172.200.2.81",
"172.200.2.73",
"172.200.2.70",
"172.200.2.62",
]
for i in search_clientip:
print(i)
subprocess.run([r"C:\Users\dso\Downloads\scrcpy-win64-v3.3.2\scrcpy-win64-v3.3.2\scrcpy.exe", "-s", i])
<?xml version='1.0' encoding='UTF-8' standalone='yes' ?>
<hierarchy rotation="0">
<node index="0" text="" resource-id="" class="android.widget.LinearLayout" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[0,2118][1080,2248]" drawing-order="0" hint="">
<node index="0" text="" resource-id="com.android.systemui:id/rot0" class="android.widget.FrameLayout" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[0,2118][1080,2248]" drawing-order="1" hint="">
<node index="0" text="" resource-id="com.android.systemui:id/deadzone" class="android.view.View" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[0,2118][1080,2248]" drawing-order="3" hint="" />
<node index="1" text="" resource-id="com.android.systemui:id/nav_buttons" class="android.widget.LinearLayout" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[0,2118][1080,2248]" drawing-order="1" hint="">
<node index="0" text="" resource-id="com.android.systemui:id/start_padding" class="android.widget.FrameLayout" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[0,2118][233,2248]" drawing-order="1" hint="" />
<node index="1" text="" resource-id="com.android.systemui:id/recent_apps" class="android.widget.ImageView" package="com.android.systemui" content-desc="概览" checkable="false" checked="false" clickable="true" enabled="true" focusable="true" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[230,2118][395,2245]" drawing-order="2" hint="" />
<node index="2" text="" resource-id="com.android.systemui:id/home" class="android.widget.ImageView" package="com.android.systemui" content-desc="主屏幕" checkable="false" checked="false" clickable="true" enabled="true" focusable="true" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[454,2118][619,2245]" drawing-order="4" hint="" />
<node index="3" text="" resource-id="com.android.systemui:id/back" class="android.widget.ImageView" package="com.android.systemui" content-desc="返回" checkable="false" checked="false" clickable="true" enabled="true" focusable="true" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[678,2118][843,2245]" drawing-order="6" hint="" />
<node index="4" text="" resource-id="com.android.systemui:id/side_padding" class="android.widget.FrameLayout" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[846,2118][1080,2248]" drawing-order="7" hint="" />
</node>
</node>
</node>
<node index="0" text="" resource-id="" class="android.widget.FrameLayout" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[0,0][1080,89]" drawing-order="0" hint="">
<node index="1" text="" resource-id="com.android.systemui:id/scrim_behind" class="android.view.View" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[0,0][1080,89]" drawing-order="2" hint="" />
<node index="2" text="" resource-id="com.android.systemui:id/scrim_in_front" class="android.view.View" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[0,0][1080,89]" drawing-order="9" hint="" />
<node index="3" text="" resource-id="" class="android.view.View" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[0,0][1080,89]" drawing-order="11" hint="" />
<node index="4" text="" resource-id="com.android.systemui:id/status_bar_container" class="android.widget.FrameLayout" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[0,0][1080,89]" drawing-order="4" hint="">
<node index="0" text="" resource-id="com.android.systemui:id/status_bar" class="android.widget.FrameLayout" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[0,0][1077,86]" drawing-order="1" hint="">
<node index="0" text="" resource-id="com.android.systemui:id/phone_status_bar_contents_container" class="android.widget.LinearLayout" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[16,0][1058,86]" drawing-order="3" hint="">
<node index="0" text="" resource-id="com.android.systemui:id/clock_container" class="android.widget.FrameLayout" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[24,3][228,86]" drawing-order="1" hint="">
<node index="0" text="" resource-id="com.android.systemui:id/leftside" class="android.widget.LinearLayout" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[24,3][228,86]" drawing-order="1" hint="">
<node index="0" text="下午5:09" resource-id="com.android.systemui:id/clock" class="android.widget.TextView" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[47,3][205,86]" drawing-order="10" hint="" />
</node>
</node>
<node index="1" text="" resource-id="" class="android.widget.FrameLayout" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[228,3][850,86]" drawing-order="2" hint="" />
<node index="2" text="" resource-id="com.android.systemui:id/system_icon_area" class="android.widget.LinearLayout" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[850,3][1046,86]" drawing-order="3" hint="">
<node index="0" text="" resource-id="com.android.systemui:id/system_icons" class="android.widget.LinearLayout" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="true" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[850,14][1046,74]" drawing-order="1" hint="">
<node index="0" text="" resource-id="com.android.systemui:id/signal_cluster_view" class="android.widget.LinearLayout" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[850,16][962,72]" drawing-order="5" hint="">
<node index="0" text="" resource-id="com.android.systemui:id/signal_cluster" class="android.widget.LinearLayout" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="true" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[850,16][962,72]" drawing-order="1" hint="">
<node index="0" text="" resource-id="com.android.systemui:id/mobile_signal_group_0" class="android.widget.LinearLayout" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="true" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[850,16][904,72]" drawing-order="4" hint="">
<node index="0" text="" resource-id="com.android.systemui:id/mobile_combo" class="android.widget.LinearLayout" package="com.android.systemui" content-desc="4G 手机信号满格。" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[850,16][904,72]" drawing-order="1" hint="">
<node index="0" text="" resource-id="" class="android.widget.FrameLayout" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[850,16][904,72]" drawing-order="6" hint="">
<node index="0" text="" resource-id="" class="android.widget.FrameLayout" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[850,16][904,72]" drawing-order="1" hint="">
<node index="0" text="" resource-id="com.android.systemui:id/notch_volte" class="android.widget.ImageView" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[850,16][904,72]" drawing-order="1" hint="" />
<node index="1" text="" resource-id="com.android.systemui:id/mobile_signal" class="android.widget.ImageView" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[850,16][904,72]" drawing-order="4" hint="" />
</node>
</node>
</node>
</node>
<node index="1" text="" resource-id="com.android.systemui:id/wifi_combo" class="android.widget.FrameLayout" package="com.android.systemui" content-desc="WLAN 信号满格。" checkable="false" checked="false" clickable="false" enabled="true" focusable="true" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[904,16][962,72]" drawing-order="14" hint="">
<node index="0" text="" resource-id="com.android.systemui:id/wifi_signal" class="android.widget.ImageView" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[904,16][962,72]" drawing-order="1" hint="" />
<node index="1" text="" resource-id="com.android.systemui:id/wifi_inout" class="android.widget.ImageView" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[936,16][962,72]" drawing-order="3" hint="" />
</node>
</node>
</node>
<node index="1" text="" resource-id="com.android.systemui:id/battery" class="android.widget.LinearLayout" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="true" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[962,14][1046,74]" drawing-order="6" hint="">
<node index="0" text="" resource-id="" class="android.widget.FrameLayout" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[962,16][1046,72]" drawing-order="1" hint="">
<node index="0" text="" resource-id="com.android.systemui:id/battery_image" class="android.widget.ImageView" package="com.android.systemui" content-desc="正在充电,已完成百分之100。" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[962,16][1046,72]" drawing-order="1" hint="" />
<node index="1" text="100" resource-id="com.android.systemui:id/battery_digit" class="android.widget.TextView" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[982,16][1020,72]" drawing-order="3" hint="" />
</node>
</node>
</node>
</node>
</node>
</node>
</node>
</node>
</hierarchy>
\ No newline at end of file
"""代理后端卡顿回归测试;使用真实 HTTPFlow,存储服务全部替换为本地模拟。"""
import asyncio
import json
import threading
import time
import unittest
from unittest.mock import MagicMock, patch
from mitmproxy import connection, http
import http_lanjie_keyword_proxy as keyword_proxy
import http_lanjie_user as user_proxy
MODULES = (user_proxy, keyword_proxy)
PHONE_IP = "192.0.2.10"
def make_flow(module, target=True):
flow = http.HTTPFlow(
connection.Client(peername=(PHONE_IP, 12345), sockname=("127.0.0.1", 8080)),
connection.Server(address=("example.test", 443)),
)
if not target:
path, data = "/unrelated", {"ok": True}
elif module is user_proxy:
path = "/api/sns/v4/note/user/posted?user_id=user-1"
data = {
"data": {
"has_more": True,
"notes": [{
"user": {"userid": "user-1", "nickname": "test"},
"id": "note-1", "title": "title", "desc": "description",
"type": "normal", "images_list": [{"url": "https://example.test/image"}],
"create_time": 1700000000,
}],
}
}
else:
path = "/api/sns/v10/search/notes?keyword=test"
data = {
"data": {"items": [{
"model_type": "note",
"note": {"id": "note-1", "user": {"userid": "user-1"}, "timestamp": 1700000000},
}]}
}
flow.request = http.Request.make("GET", f"https://example.test{path}")
flow.response = http.Response.make(200, json.dumps(data), {"Content-Type": "application/json"})
return flow
def tearDownModule():
for module in MODULES:
for addon in module.addons:
addon.done()
addon._response_executor.shutdown(wait=True)
class ProxyResponsivenessTests(unittest.IsolatedAsyncioTestCase):
async def asyncSetUp(self):
self.addons = []
def make_addon(self, module):
addon = module.Counter()
self.addons.append(addon)
addon.db = MagicMock()
addon.redis_conn = MagicMock()
addon.redis_conn2 = MagicMock()
return addon
async def asyncTearDown(self):
for addon in self.addons:
addon.done()
await asyncio.to_thread(addon._response_executor.shutdown, wait=True)
async def assert_backend_does_not_block_proxy(self, module, backend):
addon = self.make_addon(module)
entered, release = threading.Event(), threading.Event()
def stall(*args, **kwargs):
entered.set()
release.wait(timeout=2)
if backend == "mysql":
addon.db.replace_into.side_effect = stall
else:
redis = addon.redis_conn2 if module is user_proxy else addon.redis_conn
redis.hset.side_effect = stall
task = asyncio.create_task(addon.response(make_flow(module)))
try:
self.assertTrue(await asyncio.to_thread(entered.wait, 1))
# 后端仍在等待时,无关请求必须能够完成,事件循环也必须继续调度。
await asyncio.wait_for(addon.response(make_flow(module, target=False)), timeout=0.2)
await asyncio.sleep(0.02)
self.assertFalse(task.done(), "存储任务应仍在等待,不能靠等待结束后才转发其他请求")
finally:
release.set()
await asyncio.wait_for(task, timeout=2)
async def test_slow_mysql_keeps_other_requests_responsive(self):
for module in MODULES:
with self.subTest(module=module.__name__):
await self.assert_backend_does_not_block_proxy(module, "mysql")
async def test_slow_redis_keeps_other_requests_responsive(self):
for module in MODULES:
with self.subTest(module=module.__name__):
await self.assert_backend_does_not_block_proxy(module, "redis")
async def test_concurrent_responses_preserve_counts_and_serialize_writes(self):
for module in MODULES:
with self.subTest(module=module.__name__):
addon = self.make_addon(module)
active, max_active = 0, 0
lock = threading.Lock()
def write(*args):
nonlocal active, max_active
with lock:
active += 1
max_active = max(max_active, active)
time.sleep(0.01)
with lock:
active -= 1
addon.db.replace_into.side_effect = write
await asyncio.gather(*(addon.response(make_flow(module)) for _ in range(4)))
self.assertEqual(max_active, 1)
self.assertEqual(addon.db.replace_into.call_count, 8)
if module is user_proxy:
counts = [c.args[2] for c in addon.redis_conn2.hset.call_args_list if isinstance(c.args[2], int)]
else:
counts = [c.args[2] for c in addon.redis_conn.hset.call_args_list if isinstance(c.args[2], int)]
self.assertEqual(counts, [1, 2, 3, 4])
self.assertEqual(
addon.db.replace_into.call_args_list[0].args[1][0]["video_id"], "note-1"
)
async def test_failed_write_does_not_mark_collection_successful(self):
for module in MODULES:
with self.subTest(module=module.__name__):
addon = self.make_addon(module)
addon.db.replace_into.side_effect = TimeoutError("simulated database timeout")
await addon.response(make_flow(module))
if module is user_proxy:
self.assertEqual(addon.redis_conn2.hset.call_args_list[-1].args[2], "0")
else:
self.assertEqual(addon.redis_conn.hset.call_args_list[-1].args[2], "0")
async def test_unrelated_or_missing_responses_do_not_access_storage(self):
for module in MODULES:
with self.subTest(module=module.__name__):
addon = self.make_addon(module)
await addon.response(make_flow(module, target=False))
flow = make_flow(module)
flow.response = None
await addon.response(flow)
addon.db.replace_into.assert_not_called()
addon.redis_conn.hset.assert_not_called()
addon.redis_conn2.hset.assert_not_called()
class MySQLRecoveryTests(unittest.TestCase):
def test_initialization_is_lazy_and_timeouts_are_finite(self):
for module in MODULES:
with self.subTest(module=module.__name__), patch.object(module.pymysql, "connect") as connect:
db = module.SimpleMySQL()
connect.assert_not_called()
db._ensure_conn()
for option in ("connect_timeout", "read_timeout", "write_timeout"):
self.assertGreater(connect.call_args.kwargs[option], 0)
db.close()
def test_reconnect_keeps_the_new_connection(self):
for module in MODULES:
with self.subTest(module=module.__name__):
db = module.SimpleMySQL()
old_connection, new_connection = MagicMock(), MagicMock()
old_connection.ping.side_effect = OSError("connection lost")
db._conn = old_connection
with patch.object(module.pymysql, "connect", return_value=new_connection):
db._ensure_conn()
self.assertIs(db._conn, new_connection)
db.close()
def test_write_failure_is_propagated_instead_of_silently_reconnecting(self):
for module in MODULES:
with self.subTest(module=module.__name__):
db = module.SimpleMySQL()
db._conn = MagicMock()
cursor = db._conn.cursor.return_value.__enter__.return_value
cursor.executemany.side_effect = module.OperationalError(2013, "simulated write failure")
with patch.object(module.pymysql, "connect") as reconnect:
with self.assertRaises(module.OperationalError):
db.replace_into("test_table", [{"id": "note-1"}])
reconnect.assert_not_called()
db.close()
if __name__ == "__main__":
unittest.main()
search_clientip = [
# "172.200.2.179",
# "172.200.2.109",
# "172.200.2.210",
# "172.200.2.118",
# "172.200.2.74",
# "172.200.2.132",
# "172.200.2.83",
# "172.200.2.75",
# "172.200.2.126",
# "172.200.2.81",
# "172.200.2.70",
# "172.200.4.43",
# "172.200.4.126",
# "172.200.4.11",
# "172.200.2.196",
# "172.200.4.37",
# "172.200.4.6",
]
user_clientip = [
# "172.200.2.210",
# "172.200.4.16",
# "172.200.4.17"
"172.20.1.254",
"172.20.1.253"
]
client_account = {
# "172.200.2.210": "15321592091",
# "172.200.2.109": "17347928573",
"172.200.4.11": "15313528920",
"172.200.2.62": "17701126712",
"172.200.4.18": "15321501171",
"172.200.2.179": "17701081357",
"172.200.2.196": "17701372219",
"172.200.4.37": "17710060291",
"172.200.4.6": "15321017103",
}
client_proxy = {
"172.200.2.210": "36.137.241.163:16817",
"172.200.2.119": "",
"172.200.2.179": "",
}
-----BEGIN CERTIFICATE-----
MIIDNTCCAh2gAwIBAgIUB4W0ull6dSleyD9ho9ToZzIoNEAwDQYJKoZIhvcNAQEL
BQAwKDESMBAGA1UEAwwJbWl0bXByb3h5MRIwEAYDVQQKDAltaXRtcHJveHkwHhcN
MjYwNTA0MTc1NjIzWhcNMzYwNTAzMTc1NjIzWjAoMRIwEAYDVQQDDAltaXRtcHJv
eHkxEjAQBgNVBAoMCW1pdG1wcm94eTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCC
AQoCggEBAL6zCRtG8y/CnwUJXTL4mh93uoklDifFEypITCsnk6baHzQPN3eW9TPc
vt8U+1K/q3d6HeIY3zV0S5aEkB2iyXA6i8JjOA/UYYAL6kO2p+9h2nvD/nKyjm6T
nIDEP+/t4QVtS0ejfgho/ASLMk+0B/cwz8DIXGqRorZCxR1A0jbkM2KFGh5xoUlf
q/2eCHEVZB6wI51rpHeNQRtlo/dXH6W1eEifsR+QaRSv0V3A0/q3t8QxyL1pBk1G
8kOAOk5JPJsvfTMDfuXwYTrh+nuynahSp8WRS0YNDPgqAuvDdx92f6xsW572Qd6L
yixbLsd6fxyoIj/OZm3EB+BJeEUJf0ECAwEAAaNXMFUwDwYDVR0TAQH/BAUwAwEB
/zATBgNVHSUEDDAKBggrBgEFBQcDATAOBgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYE
FJ691AbhEI4DSoPI1HZzdCiEJOfNMA0GCSqGSIb3DQEBCwUAA4IBAQCNBELVzv6+
YlrS+yWQvoTp49/4tCIFkOdYTOOttGYNumAjnMFbeLbJtq0exR0TpHqCjeH8G3cs
ay9NpobhAlsS5CLmwwXCnHyCHGHJrrLjGpKbFNBtj5j8FQoqoPNSNDq8dZ3dlzM/
aJX4TP0RbSfz0qhLiHKdGfEi3rRmZ+1Fo8HeYmo14W1VuLEJ0H0Zzq2IYj5fw75E
g2uj1Q/9GzIDzqL/QX2hNUY1fvez1/a+lVJr0CcQUHARwdrvk4vFsHqgY1adyOoF
H1GUL/NzlAO6COyrMeuOfFB3FzBQNanq40FPCfBP86dxYeptUHt2/6gUU5CkbowD
rdePcUaopnen
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
MIIDNTCCAh2gAwIBAgIUB4W0ull6dSleyD9ho9ToZzIoNEAwDQYJKoZIhvcNAQEL
BQAwKDESMBAGA1UEAwwJbWl0bXByb3h5MRIwEAYDVQQKDAltaXRtcHJveHkwHhcN
MjYwNTA0MTc1NjIzWhcNMzYwNTAzMTc1NjIzWjAoMRIwEAYDVQQDDAltaXRtcHJv
eHkxEjAQBgNVBAoMCW1pdG1wcm94eTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCC
AQoCggEBAL6zCRtG8y/CnwUJXTL4mh93uoklDifFEypITCsnk6baHzQPN3eW9TPc
vt8U+1K/q3d6HeIY3zV0S5aEkB2iyXA6i8JjOA/UYYAL6kO2p+9h2nvD/nKyjm6T
nIDEP+/t4QVtS0ejfgho/ASLMk+0B/cwz8DIXGqRorZCxR1A0jbkM2KFGh5xoUlf
q/2eCHEVZB6wI51rpHeNQRtlo/dXH6W1eEifsR+QaRSv0V3A0/q3t8QxyL1pBk1G
8kOAOk5JPJsvfTMDfuXwYTrh+nuynahSp8WRS0YNDPgqAuvDdx92f6xsW572Qd6L
yixbLsd6fxyoIj/OZm3EB+BJeEUJf0ECAwEAAaNXMFUwDwYDVR0TAQH/BAUwAwEB
/zATBgNVHSUEDDAKBggrBgEFBQcDATAOBgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYE
FJ691AbhEI4DSoPI1HZzdCiEJOfNMA0GCSqGSIb3DQEBCwUAA4IBAQCNBELVzv6+
YlrS+yWQvoTp49/4tCIFkOdYTOOttGYNumAjnMFbeLbJtq0exR0TpHqCjeH8G3cs
ay9NpobhAlsS5CLmwwXCnHyCHGHJrrLjGpKbFNBtj5j8FQoqoPNSNDq8dZ3dlzM/
aJX4TP0RbSfz0qhLiHKdGfEi3rRmZ+1Fo8HeYmo14W1VuLEJ0H0Zzq2IYj5fw75E
g2uj1Q/9GzIDzqL/QX2hNUY1fvez1/a+lVJr0CcQUHARwdrvk4vFsHqgY1adyOoF
H1GUL/NzlAO6COyrMeuOfFB3FzBQNanq40FPCfBP86dxYeptUHt2/6gUU5CkbowD
rdePcUaopnen
-----END CERTIFICATE-----
-----BEGIN RSA PRIVATE KEY-----
MIIEogIBAAKCAQEAvrMJG0bzL8KfBQldMviaH3e6iSUOJ8UTKkhMKyeTptofNA83
d5b1M9y+3xT7Ur+rd3od4hjfNXRLloSQHaLJcDqLwmM4D9RhgAvqQ7an72Hae8P+
crKObpOcgMQ/7+3hBW1LR6N+CGj8BIsyT7QH9zDPwMhcapGitkLFHUDSNuQzYoUa
HnGhSV+r/Z4IcRVkHrAjnWukd41BG2Wj91cfpbV4SJ+xH5BpFK/RXcDT+re3xDHI
vWkGTUbyQ4A6Tkk8my99MwN+5fBhOuH6e7KdqFKnxZFLRg0M+CoC68N3H3Z/rGxb
nvZB3ovKLFsux3p/HKgiP85mbcQH4El4RQl/QQIDAQABAoIBAF2mfdPj+XycdsyZ
5yend8T5XuWICZYVTc6nd6R/yJ6ZotZFnMdBnsRr5V6Xpr7h+vpvQaqt7TwKky5l
hoLPVV6kmcsKP9diRMmF0HOViY5hP1MlktlP/+uk2ShReFbDOw0Xue8CBtxpdk5i
73+92WWXFofFvcDmKYKZcsTldvbWLDWxS4azkArZnYA6154xzorGJusg46oyZBYp
K4993GYb4ZrARoL+mgwuOoUAKsyk0T0e0D6/qxhyZXsgtRP+gfJDNXLK2hxJ9HaN
kDGHp3uKuf01AYVAxCv2gFrfmItq8E/fofSSt4GuE+chyffuzW2H1O1nWCC/Xcmo
wdNwPKMCgYEA7FrErrAMKuD3D5YmNcX42wwFQZ+6siOWmadbs8bUWMGrm7ZytbEV
+C5a/JVteZNxA6JWssiIFa7VoHvHXDpNuJCi3vxgywWIpSMeauiTeJZKnPo5i3e3
PlvO0uX0naPBtaeDkK4dUVbrtCgfXT8xv9vdPzBOXDkBVWQBrMiWng8CgYEAzozM
7QES7a5M52WjzXVJUcBRF0gPWRQw1BReTVPDo8saopuujpXAPgLI/OS3ZuKNb8+H
sRDVjQMlZti06qfqt5T2RnCB6pyjr+Mbd9Cf0JmSf+dUVs4pcYaPe8hrGOrZetE8
WCkzfSXaNdDF2IrLp0fYhUuXbcNrBsJmWc7YXa8CgYBpxeE5UB3R3qWSOx7Ud8l7
tfBwQtxZNmYCU4xNcxC6u8lhwQ+q0hpD2/LqELFSdDJibvcfwXBtS7XcwSgh1RHN
JCVPZ2Cl2s8hIAtPys+cap3vjGfOS4AdDxcK+NA08AETm2jciZ8jNKP9FuuaXlqU
Qv/LdIHM8dHv9fZt7cLB7wKBgEX13vtv369t2FKQVLkkvt7X2x+dosUzV46eD4r1
klCKXM0zGh7ljiXy34z5Ez3gArQagQVyhEKtDCAXyr+ofJIN/JTDSt3ijHbo38bn
fRo0yjBUdHaqgdMYFsWAjvXzphI5iMz7t5ruFUkhG8JK0MwqQ6ZygioFhNzXP7+v
lg21AoGADGr4VWL3KpPwozdZe6G0tiZNzRpO7uP4Fmrt9s3FmBoBt1qOWDj/jt54
Ln/hi1pIfhnRbWSnjkL1BEsHCbldF8tKb/lztgoVeSTjDvX4fMTT2OrqAsvcn/Tf
gwhdjiBU8WyQi38MgrP9dyBs3AflADu/p8SkZBsBEvS0Oz8sIpM=
-----END RSA PRIVATE KEY-----
-----BEGIN CERTIFICATE-----
MIIDNTCCAh2gAwIBAgIUB4W0ull6dSleyD9ho9ToZzIoNEAwDQYJKoZIhvcNAQEL
BQAwKDESMBAGA1UEAwwJbWl0bXByb3h5MRIwEAYDVQQKDAltaXRtcHJveHkwHhcN
MjYwNTA0MTc1NjIzWhcNMzYwNTAzMTc1NjIzWjAoMRIwEAYDVQQDDAltaXRtcHJv
eHkxEjAQBgNVBAoMCW1pdG1wcm94eTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCC
AQoCggEBAL6zCRtG8y/CnwUJXTL4mh93uoklDifFEypITCsnk6baHzQPN3eW9TPc
vt8U+1K/q3d6HeIY3zV0S5aEkB2iyXA6i8JjOA/UYYAL6kO2p+9h2nvD/nKyjm6T
nIDEP+/t4QVtS0ejfgho/ASLMk+0B/cwz8DIXGqRorZCxR1A0jbkM2KFGh5xoUlf
q/2eCHEVZB6wI51rpHeNQRtlo/dXH6W1eEifsR+QaRSv0V3A0/q3t8QxyL1pBk1G
8kOAOk5JPJsvfTMDfuXwYTrh+nuynahSp8WRS0YNDPgqAuvDdx92f6xsW572Qd6L
yixbLsd6fxyoIj/OZm3EB+BJeEUJf0ECAwEAAaNXMFUwDwYDVR0TAQH/BAUwAwEB
/zATBgNVHSUEDDAKBggrBgEFBQcDATAOBgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYE
FJ691AbhEI4DSoPI1HZzdCiEJOfNMA0GCSqGSIb3DQEBCwUAA4IBAQCNBELVzv6+
YlrS+yWQvoTp49/4tCIFkOdYTOOttGYNumAjnMFbeLbJtq0exR0TpHqCjeH8G3cs
ay9NpobhAlsS5CLmwwXCnHyCHGHJrrLjGpKbFNBtj5j8FQoqoPNSNDq8dZ3dlzM/
aJX4TP0RbSfz0qhLiHKdGfEi3rRmZ+1Fo8HeYmo14W1VuLEJ0H0Zzq2IYj5fw75E
g2uj1Q/9GzIDzqL/QX2hNUY1fvez1/a+lVJr0CcQUHARwdrvk4vFsHqgY1adyOoF
H1GUL/NzlAO6COyrMeuOfFB3FzBQNanq40FPCfBP86dxYeptUHt2/6gUU5CkbowD
rdePcUaopnen
-----END CERTIFICATE-----
-----BEGIN DH PARAMETERS-----
MIICCAKCAgEAyT6LzpwVFS3gryIo29J5icvgxCnCebcdSe/NHMkD8dKJf8suFCg3
O2+dguLakSVif/t6dhImxInJk230HmfC8q93hdcg/j8rLGJYDKu3ik6H//BAHKIv
j5O9yjU3rXCfmVJQic2Nne39sg3CreAepEts2TvYHhVv3TEAzEqCtOuTjgDv0ntJ
Gwpj+BJBRQGG9NvprX1YGJ7WOFBP/hWU7d6tgvE6Xa7T/u9QIKpYHMIkcN/l3ZFB
chZEqVlyrcngtSXCROTPcDOQ6Q8QzhaBJS+Z6rcsd7X+haiQqvoFcmaJ08Ks6LQC
ZIL2EtYJw8V8z7C0igVEBIADZBI6OTbuuhDwRw//zU1uq52Oc48CIZlGxTYG/Evq
o9EWAXUYVzWkDSTeBH1r4z/qLPE2cnhtMxbFxuvK53jGB0emy2y1Ei6IhKshJ5qX
IB/aE7SSHyQ3MDHHkCmQJCsOd4Mo26YX61NZ+n501XjqpCBQ2+DfZCBh8Va2wDyv
A2Ryg9SUz8j0AXViRNMJgJrr446yro/FuJZwnQcO3WQnXeqSBnURqKjmqkeFP+d8
6mk2tqJaY507lRNqtGlLnj7f5RNoBFJDCLBNurVgfvq9TCVWKDIFD4vZRjCrnl6I
rD693XKIHUCWOjMh1if6omGXKHH40QuME2gNa50+YPn1iYDl88uDbbMCAQI=
-----END DH PARAMETERS-----
import datetime
import multiprocessing
import random
import traceback
import requests
import uiautomator2 as u2
from redis import Redis
import re
import time
import pymysql
from pymysql.err import OperationalError
from loguru import logger
import frida
import sys
import json
# ===================== 全局配置 =====================
KEYCODE_MAP = {
"0": 7, "1": 8, "2": 9, "3": 10, "4": 11,
"5": 12, "6": 13, "7": 14, "8": 15, "9": 16
}
redis_conn3 = Redis(host="172.16.0.24", password="aiyingli@@123", db=3, decode_responses=True)
common_redis0 = Redis(host="172.16.0.24", password="aiyingli@@123", db=0, decode_responses=True)
redis_conn2 = Redis(host="172.16.0.24", password="aiyingli@@123", db=2, decode_responses=True)
SCRIPT_FILE = "hook_dlopen.js"
PACKAGE_NAME = "com.xingin.xhs"
from tools import client_account, user_clientip, client_proxy
import subprocess
FRIDA_SERVER_PATH = "/data/local/tmp/frida-server-16.7.19-android-arm64"
LOCAL_FRIDA_SERVER = "frida-server-16.7.19-android-arm64" # 本地文件路径,改成你的实际路径
search_clientip = [
# "172.200.2.179",
# "172.200.2.109",
# "172.200.2.210",
# "172.200.2.118",
# "172.200.2.74",
# "172.200.2.132",
# "172.200.2.83",
# "172.200.2.75",
# "172.200.2.126",
# "172.200.2.81",
# "172.200.2.70",
# "172.200.4.18",
# "172.200.4.126",
# "172.200.4.11",
# # "172.200.2.196",
# "18910081473": "http://iprowq:yk2gbxo4@111.170.157.180:16816 ",
# "172.200.4.115",
# "18911415293": "http://iprowq:yk2gbxo4@42.51.0.234:16816 ",
# "172.200.4.155",
# "172.200.4.13",
# "18911482557": "http://iprowq:yk2gbxo4@117.50.201.181:16816 ",
# "172.200.5.70",
# "18911475707": "http://iprowq:yk2gbxo4@36.134.120.81:16816 ",
# "172.200.5.98",
# "18911461625": "http://iprowq:yk2gbxo4@42.51.42.254:16818 ",
# "172.200.4.6",
# "172.200.4.18",
# "172.200.4.37",
# "172.200.4.13"
# "172.200.4.16",
"172.200.4.43",
"172.200.4.40",
# "172.200.5.215",
# '172.200.4.2'
"172.200.4.26",
# "172.200.4.38",
"172.200.5.0",
"172.200.4.252",
"172.200.4.214",
"172.200.4.23",
"172.200.4.24",
"172.200.4.31",
# "172.200.4.39",
]
wait_set_phone = [
"172.200.4.155",
"172.200.5.98",
"172.200.5.99",
"172.200.5.70"
]
frida_port = "27042"
def setup_logger(ip):
"""为每台手机创建独立的日志文件"""
log_file = f"xhs_log_{ip.replace('.', '_')}.log"
# 移除默认 logger,添加文件输出
logger.remove() # 移除默认 stdout
# logger.add(log_file, rotation="10 MB", retention="7 days", encoding="utf-8")
logger.add(sys.stderr, level="INFO") # 保留终端关键输出
return logger
class SimpleMySQL:
"""极简查询封装:只支持 SELECT * … WHERE ..."""
def __init__(self, charset="utf8mb4"):
self.cfg = dict(host="tenant-2101894307-cn-beijing-public.bytehouse.volces.com", port=3306, user="bytehouse",
password="m1wUyPHX0H:JQDqesXaoc", db="douchacha_data", charset=charset,
cursorclass=pymysql.cursors.DictCursor,
autocommit=True
)
self._conn = None
self._connect()
# ---------- public ----------
def query(self, phone_num, start_time, deadline):
sql = f"SELECT * FROM recv_sms WHERE phone_num = {phone_num} AND recv_time >= {start_time} AND recv_time <= {deadline}"
try:
return self._execute(sql)
except OperationalError as e: # 连接异常自动重连一次
print(e)
if e.args and e.args[0] in (2006, 2013):
self._reconnect()
return self._execute(sql)
raise
# ---------- private ----------
def _connect(self):
if self._conn:
self._conn.close()
self._conn = pymysql.connect(**self.cfg)
def _reconnect(self):
try:
self._connect()
except Exception as e:
raise RuntimeError(f"Reconnect failed: {e}") from e
def _execute(self, sql):
with self._conn.cursor() as cur:
cur.execute(sql)
return cur.fetchall()
def close(self):
self._conn.close()
def _ensure_conn(self):
try:
self._conn.ping(reconnect=True) # 如果断了会自动重连
except Exception as e:
logger.error(f"MySQL ping failed, reconnecting: {e}")
self._conn = self._connect() # 你自己封装的重连逻辑
def replace_into(self, table, item_list):
self._ensure_conn()
if not item_list:
return 0
try:
keys = list(item_list[0].keys())
cols = ", ".join(f"`{k}`" for k in keys)
placeholders = ", ".join(["%s"] * len(keys))
sql = f"REPLACE INTO `{table}` ({cols}) VALUES ({placeholders})"
# 处理特殊字符
def sanitize_value(value):
if value is None:
return None
if isinstance(value, str):
# 移除或转义可能引起问题的字符
return value.replace('`', '').replace('\\', '\\\\')
return value
values = [tuple(sanitize_value(item[k]) for k in keys) for item in item_list]
try:
# 🔑 关键:写之前先 ping 一下,断了就重连
self._conn.ping(reconnect=True)
with self._conn.cursor() as cur:
cur.executemany(sql, values)
# self._conn.commit()
logger.success(f"********** {table} 共写入{len(item_list)}条数据 **********")
return len(values)
except Exception as e:
logger.error(f"MySQL 执行错误: {e}")
raise
except Exception as e:
print(f"Error: {e}")
self._connect()
db = SimpleMySQL()
def alert(msg):
url = "https://open.feishu.cn/open-apis/bot/v2/hook/1ac7eee2-1c29-477f-95f1-8f3f7df4a0b7 "
payload = {
"msg_type": "text",
"content": {
"text": msg
}
}
try:
resp = requests.post(
url,
json=payload,
headers={"Content-Type": "application/json"},
timeout=10
)
resp.raise_for_status()
logger.info("Feishu alert sent, status=%s", resp.status_code)
except requests.RequestException as e:
logger.error("Feishu alert failed: %s", e)
class Login():
def __init__(self, client_ip):
self.client_ip = client_ip
def login(self, d, client_ip):
while 1:
page_activity = check_activity(d)
logger.success(page_activity)
if page_activity == "com.xingin.login.activity.WelcomeActivity":
# 微信登陆界面
dump_page(d, "WelcomeActivity")
if d(text="一键登录"):
logger.success("开始使用一键登录")
d.xpath('//android.widget.LinearLayout/android.widget.Button[@index="0"]').click()
time.sleep(2)
d(text="一键登录").click()
time.sleep(3)
if d(text='同意并继续'):
d(text="同意并继续").click()
time.sleep(2)
elif d(text="手机号登录").exists:
logger.success("找到使用手机号登录,开始点击操作")
d(text="手机号登录").click()
time.sleep(3)
else:
logger.error("未找到手机号登录选项,需要单独处理")
elif page_activity == "com.xingin.login.halfwelcome.HalfWelcomeActivity":
# 当前页面仅有手机号登陆
dump_page(d, "HalfWelcomeActivity")
if d(text="手机号登录").exists:
logger.success("找到手机号登录,开始点击操作")
d(text="手机号登录").click()
time.sleep(3)
else:
logger.error("未找到手机号登录选项,需要单独处理")
elif page_activity == "com.xingin.login.activity.LoginActivity":
# 手机号登陆界面
# dump_page(d,"LoginActivity")
# logger.success("写入完成")
# exit()
# time.sleep(3)
if d(description="全部删除").exists:
try:
phone_number = d(textMatches="\\d{3} \\d{4} \\d{4}").get_text()
logger.success(f"当前手机号为{phone_number}")
except:
phone_number = ""
if phone_number != "":
logger.error("直接发送短信")
logger.success("找到 全部删除 开始点击")
d(description="全部删除").click()
time.sleep(2)
el = d.xpath('//android.widget.EditText[@hint="请输入手机号码"]')
if el:
el.click()
phone = client_account[client_ip]
for char in phone:
d.send_keys(char)
time.sleep(0.1)
else:
logger.error("没有找到 el")
d(description="未选中,同意").click()
time.sleep(1)
# 4. 点击 "验证并登录"
d(text="验证并登录").click()
time.sleep(1)
account = client_account[client_ip]
code = ""
for attempt in range(1, 4):
if attempt != 1:
d(text="重新发送").click()
time.sleep(2)
logger.info(f"=== 第 {attempt} 次尝试登陆 {account} ===")
start_time = int(time.time())
deadline = start_time + 60
while time.time() < deadline:
rows = db.query(account, start_time, deadline)
if rows:
msg = rows[0]["msg"]
code = re.search(r"\b(\d{4,6})\b", msg).group(1)
break
time.sleep(3)
if not code:
logger.warning(f"{account} 第 {attempt} 次未获取到验证码,准备重试")
continue
# if attempt == MAX_RETRY:
break
if code == "":
return
logger.success(f"{account} 获取验证码成功:{code}")
d(text="输入验证码").click()
time.sleep(1)
for char in code:
d.send_keys(char)
time.sleep(0.1)
d(text="登录").click()
time.sleep(3)
elif page_activity == "com.xingin.login.device.offline.DeviceOfflineRemindActivity":
if d(text="账号下线提示"):
logger.error("当前弹窗登录掉线,点击重新登录")
d(text="重新登录").click()
time.sleep(3)
continue
elif page_activity == "com.xingin.reactnative.ui.WalifyReactTranslucentActivity":
logger.error("当前设备验证异常")
alert(f"小红书检测设备 {client_ip} 登陆异常,请及时查看")
set_device_status(client_ip, "0")
return
elif page_activity == "com.xingin.alioth.search.GlobalSearchActivity":
return
def check_page_status(d, client_ip):
status_count = 0
while 1:
if d(text="网络好像断了,请检查手机是否联网").exists:
status_count += 1
if status_count == 5:
logger.error("连续点击*重新加载*异常 退出当前词查询 发送报警")
return False
logger.error(f'{client_ip} 网络异常 重新等待五秒后重新点击搜索')
time.sleep(3)
if d(text="重新加载").exists:
logger.error(f"{client_ip} 当前有重新加载按钮 点击重新加载")
d(text="重新加载").click()
time.sleep(2)
continue
elif d(text="搜索").exists:
logger.error("当前网络连接异常 未找到重新加载按钮,重新点击搜索")
d(text="搜索").click()
time.sleep(2)
continue
return True
def human_like_scroll(d, keyword, client_ip, max_up=2, min_delay=2.0, max_delay=4.0):
screen_width, screen_height = d.window_size()
up_count = 0
down_count = 0
continuous_down = 0 # 连续下滑计数
random_down_threshold = random.randint(3, 5) # 触发上滑的门槛(3~5 次下滑后才允许上滑)
last_spider_count = None
last_change_time = time.time()
start_time = time.time()
max_nochange_time = 1000
last_progress_time = time.time() # 只在 spider_count 变动时更新,用于 5 分钟强恢复
while True:
try:
# TODO: 退出条件 -> redis hget(f"xhs_app:{client_ip}:{keyword}", keyword) == 5 时 break
if not check_page_status(d, client_ip):
return False
if d(text="无更多内容").exists:
logger.success("采集完成 无更多内容")
return True
elif d(text="没有找到相关内容,换个词试试吧").exists:
logger.success("没有找到相关内容,换个词试试吧")
return True
try:
spider_count = redis_conn3.hget(f"xhs_app:{client_ip}", keyword)
# logger.success(f"xhs_app:{client_ip} keyword -> {keyword} spider_count -> {spider_count}", )
if spider_count is not None:
spider_count = int(spider_count)
except Exception as e:
print(f"[Redis异常] {e}")
spider_count = None
if spider_count == 5:
# logger.success(f"{keyword} 当前已拦截5次 退出滑动")
return True
if spider_count is not None:
if spider_count != last_spider_count:
# 正常进度,更新记录
last_spider_count = spider_count
last_change_time = time.time()
else:
# 计数没变化,超过15s → 认为卡住
if time.time() - last_change_time > 200:
# print("[卡顿检测] 页面长时间无变化,触发多次上滑+强力下滑容错")
# 连续上滑 2~3 次
for _ in range(random.randint(2, 3)):
d.swipe(
screen_width // 2,
int(screen_height * 0.6),
screen_width // 2,
int(screen_height * 0.8),
0.3
)
time.sleep(0.8)
# 强力下滑(90% 屏幕高度)
d.swipe(
screen_width // 2,
int(screen_height * 0.9),
screen_width // 2,
int(screen_height * 0.1),
0.5
)
time.sleep(3)
# 重置检测计时器
last_change_time = time.time() # 默认方向下滑
if time.time() - last_progress_time > max_nochange_time:
return False
# raise TimeoutError("spider_count 长时间无变化,触发强恢复")
direction = "down"
# 控制上滑逻辑:必须连续下滑 >= 随机门槛,且上滑次数不能超过 max_up
if continuous_down >= random_down_threshold and up_count < max_up and random.random() < 0.2:
direction = "up"
up_count += 1
continuous_down = 0 # 重置连续下滑计数
random_down_threshold = random.randint(3, 5) # 重新生成门槛
else:
direction = "down"
down_count += 1
continuous_down += 1
# ---- 改进的滑动区域计算(基于屏幕中间) ----
start_x = int(screen_width * 0.5 + random.randint(-50, 50)) # 中间 ±50px
start_y = int(screen_height * (0.5 + random.uniform(-0.2, 0.2))) # 中间 ±20% 高度
if direction == "down":
move_distance = int(screen_height * random.uniform(0.5, 0.7)) # 下滑距离 50%~70%
end_y = start_y - move_distance
else:
move_distance = int(screen_height * random.uniform(0.3, 0.5)) # 上滑保持中等力度
end_y = start_y + move_distance
# 边界保护,避免滑到最顶/最底
end_y = max(100, min(screen_height - 100, end_y))
duration = float(random.uniform(0.15, 0.3)) # 更快的滑动
# 执行滑动
try:
d.swipe(start_x, start_y, start_x, end_y, duration)
except Exception as e:
print(f"[滑动异常] {e}")
# 兜底强制下滑一次,避免卡死
d.swipe(screen_width // 2, int(screen_height * 0.8), screen_width // 2, int(screen_height * 0.2), 0.3)
continue
# 模拟浏览(拟人化操作)
action_chance = random.random()
if action_chance < 0.2:
# 偶尔长时间停留(认真看内容)
delay = random.uniform(5, 8)
# logger.info(f"[拟人操作] 长时间停留 {delay:.1f}s 模拟认真看内容")
time.sleep(delay)
elif action_chance < 0.3:
# 偶尔小幅度微调滑动
offset = random.randint(50, 120)
d.swipe(start_x, start_y, start_x, start_y - offset, random.uniform(0.1, 0.2))
time.sleep(random.uniform(1, 2))
elif action_chance < 0.4:
# 偶尔什么都不做,模拟发呆
delay = random.uniform(1, 3)
# logger.info(f"[拟人操作] 发呆中 {delay:.1f}s")
time.sleep(delay)
else:
# 正常停顿浏览(快速翻页)
delay = random.uniform(1, 2.0)
time.sleep(delay)
except Exception as e:
logger.error(e)
continue
def phone_operation(d, command):
d.press(command)
def do_search_scroll(d, task, client_ip):
try:
if d(description="全部删除").exists:
d(description="全部删除").click()
logger.success("清空上次搜索内容")
if d(text="搜索, ").exists:
d(text="搜索, ").click()
for char in task:
d.send_keys(char)
time.sleep(random.uniform(0.1, 0.3))
if random.random() < 0.05:
d.send_keys(random.choice("abcdefghijklmnopqrstuvwxyz"))
time.sleep(0.1)
d.press("delete")
time.sleep(0.1)
d(text="搜索").click()
time.sleep(3)
if human_like_scroll(d, task, client_ip):
logger.info(client_ip + "操作成功")
return True
logger.error("操作失敗")
return False
else:
dump_page(d, "")
logger.success("没有找到当前按钮")
except Exception as e:
traceback.print_exc()
logger.error(e)
class StateManager:
# 当前手机状态管理 检测账号是否异常,当前函数结束时候 需要将手机保持在 搜索页面中GlobalSearchActivity
def __init__(self, client_ip):
self.client_ip = client_ip
def check_status(self, d, client_ip):
def handler_security_ui(info):
if info.get("package") == "com.lbe.security.miui":
d(resourceId="com.lbe.security.miui:id/permission_deny_button").click()
time.sleep(2)
"""检查 frida-server 进程是否在运行"""
try:
result = subprocess.run(
["adb", "-s", client_ip, "shell", "ps | grep frida-server"],
capture_output=True, text=True
)
if "frida-server" in result.stdout:
print("检测到 frida-server 进程正在运行:")
print(result.stdout.strip())
else:
return False
except Exception as e:
print(f"检查进程时出错: {e}")
return False
d.app_start("cn.ys1231.appproxy", ".MainActivity")
current = d.app_current()
if current["package"] == "cn.ys1231.appproxy" and current["activity"] == ".MainActivity":
logger.info(current)
switch = d(descriptionContains="http ")
if switch and switch.info.get("className") == "android.widget.Switch":
while True:
if not switch.info["checked"]:
switch.click()
time.sleep(2)
else:
break
recent_app = d(resourceId="com.android.systemui:id/recent_apps")
recent_app.click()
time.sleep(1)
xhs_app_card = d(description="小红书,未加锁")
xhs_app_card.click()
time.sleep(1)
info = d.app_current()
if info.get("package") == "com.xingin.xhs":
while 1:
info = d.app_current()
logger.warning(info)
activity = info.get("activity")
logger.success(f"{client_ip},{activity}")
DeviceManager.unlock(client_ip, logger)
if activity == "com.xingin.alioth.search.GlobalSearchActivity":
if d(text="服务器迷路了,晚点再试试吧").exists:
logger.error(f"{client_ip} 服务器迷路了,晚点再试试吧")
common_redis0.hset("xhs_device_status", client_ip, "0")
time.sleep(240)
continue
common_redis0.hset("xhs_device_status", client_ip, "1")
return True
elif activity in [".index.v2.IndexActivityV2", "com.xingin.xhs.index.v2.IndexActivityV2"]:
logger.success("当前手机页面处于首页,检测是否需要登陆,不需要登陆则跳转到搜索页面")
if d(text="登录发现更多精彩").exists and d(text="去登录").exists:
logger.error("当前账号掉线 重新登陆")
d(text="去登录").click()
Login(self.client_ip).login(d, client_ip)
elif d(text="账号下线提示"):
logger.error("当前弹窗登录掉线,点击重新登录")
d(text="重新登录").click()
time.sleep(3)
continue
else:
logger.success("当前无需登录,跳转到搜索页面")
if d(description="搜索").exists:
d(description="搜索").click()
time.sleep(3)
continue
elif activity in ["com.xingin.login.activity.WelcomeActivity",
"com.xingin.login.activity.LoginActivity",
"com.xingin.login.device.offline.DeviceOfflineRemindActivity",
"com.xingin.login.halfwelcome.HalfWelcomeActivity"]:
logger.success("当前正在登陆页面中,直接执行登陆程序")
Login(self.client_ip).login(d, client_ip)
elif activity == "com.xingin.reactnative.ui.WalifyReactTranslucentActivity":
logger.error("当前设备验证异常")
if d(text="当前账户异常, 允许启用本地生物验证").exists:
alert(f"小红书检测设备 {client_ip} 登陆异常 状态:当前账户异常, 允许启用本地生物验证,请及时查看")
else:
alert(f"小红书检测设备 {client_ip} 登陆异常 状态:未知状态,请及时查看")
common_redis0.hset("xhs_device_status", client_ip, "0")
return False
elif activity == "com.xingin.matrix.notedetail.NoteDetailActivity":
logger.warning(f"当前进入卡片详情页,点击退出当前页面")
d.click(44, 164)
time.sleep(3)
else:
logger.error(f"当前Activity 未处理:{activity}")
time.sleep(40)
while 1:
info = d.app_current()
logger.error(f'当前页面不在小红书中:{info.get("package")}')
for i in range(5):
phone_operation(d, 'back')
time.sleep(1)
DeviceManager.start_app(client_ip, logger)
time.sleep(5)
if info.get("package") == "com.xingin.xhs":
break
else:
logger.error(f"打开小红书失败,重新尝试,当前页面为:{info.get('package')}")
time.sleep(10)
handler_security_ui(info)
continue
else:
while 1:
info = d.app_current()
logger.error(f'当前页面不在小红书中:{info.get("package")}')
for i in range(5):
phone_operation(d, 'back')
time.sleep(1)
DeviceManager.start_app(client_ip, logger)
time.sleep(5)
if info.get("package") == "com.xingin.xhs":
break
else:
logger.error(f"打开小红书失败,重新尝试,当前页面为:{info.get('package')}")
time.sleep(10)
handler_security_ui(info)
continue
def check_collection_status(self, d):
client_status = redis_conn3.hget(f"xhs_app:status:{self.client_ip}", 'status')
if client_status == "infinity":
logger.success(f"{self.client_ip} 当前已经搜索超过上限,关闭系统等待明日采集")
DeviceManager.close_app(d)
sleep_until_next_8am()
logger.success(f"{self.client_ip} 当前完成休眠,开始继续运行")
redis_conn3.hset(f"xhs_app:status:{self.client_ip}", 'status', "success")
return False
return True
class DeviceManager:
@staticmethod
def start_app(phone_ip, logger_instance):
db = SimpleMySQL()
redis_conn = Redis(host="172.16.0.24", password="aiyingli@@123", db=3, decode_responses=True)
redis_conn2 = Redis(host="172.16.0.24", password="aiyingli@@123", db=2, decode_responses=True)
keyword_count = {}
# 重启应用的时候查看ip
d = u2.connect(f"{phone_ip}")
d.app_start("cn.ys1231.appproxy", ".MainActivity")
current = d.app_current()
switch = d(descriptionContains="http ")
if switch and switch.info.get("className") == "android.widget.Switch":
while True:
if not switch.info["checked"]:
switch.click()
time.sleep(2)
else:
logger.info("代理已开启")
break
# try:
# device = frida.get_usb_device(timeout=10,)
# print(f"[+] 已连接到设备: {device}")
# except Exception as e:
# print(f"[-] 无法连接设备: {e}")
# return
# 1. 添加远程设备(WiFi 连接)
# phone_ip = "172.200.4.115"
def handler_response(response):
try:
# logger_instance.info(response.get("url"))
# logger_instance.info(response.get("status"))
from urllib.parse import urlparse, parse_qs, parse_qsl
url = response.get("url")
# 解析 URL
parsed_url = urlparse(url)
query_params = parse_qs(parsed_url.query)
keyword = query_params["keyword"][0]
if keyword in keyword_count:
keyword_count[keyword] += 1
else:
keyword_count[keyword] = 1
count = keyword_count[keyword]
redis_conn.hset(f"xhs_app:{phone_ip}", keyword, count)
try:
response_data = json.loads(response.get("response_body"))
if response_data.get("data", {}):
items = response_data.get("data", {}).get("items", [])
if len(items) > 0:
item_list = []
for idx, item in enumerate(items):
model_type = item.get("model_type")
if model_type == "dsl" or model_type == "hot_query" or model_type == "questionnaire_survey" or model_type == "ads":
continue
try:
global_rank = (count - 1) * 20 + idx + 1
data_dic = {}
data_dic["key_word"] = keyword
data_dic["rank"] = global_rank
data_dic["video_id"] = item.get("note").get("id")
data_dic["update_pt"] = xxx(time.time()) + "00"
data_dic["create_pt"] = xxx(time.time())
item_list.append(data_dic)
except:
# logger.error(item.get("note"))
logger.success(f"{model_type} {item}")
# logger_instance.info(item_list)
db.replace_into("ods_aidso_monitor_video_rank_xhs", item_list)
# logger.success(items)
logger_instance.success(f"[{phone_ip}]:{keyword} 拦截成功 len -> {len(items)}")
else:
logger_instance.success(f"{keyword} 拦截失败")
redis_conn.hset(f"xhs_app:{phone_ip}:{keyword}", keyword, "1")
else:
logger_instance.info(response_data)
if response_data.get('msg') == "访问次数已达上限,请改天再试":
redis_conn.hset(f"xhs_app:status:{phone_ip}", "status", "infinity")
# if response_data.get("code") == 300013:
# logger.error(flow.response.json())
# if response_data.get("code") == -100:
print("获取data失败咯")
except Exception as e:
logger.error(f"解析 response 失败: {e}")
# logger.info(flow.response.text)
if keyword != '':
redis_conn.hset(f"xhs_app:{phone_ip}:{keyword}", keyword, "0")
if count == 5:
del keyword_count[keyword]
logger_instance.info(f"{phone_ip} {keyword} 达到5次, 已从 缓存 删除")
except Exception as e:
logger.error("失败")
def on_message(message, data):
"""
Frida 脚本通过 send() 发送的消息会在这里接收
如果脚本只用 console.log(),会作为 'log' 类型进来
"""
if message['type'] == 'send':
# print("[*] {0}".format(message['payload']))
response = json.loads(message['payload'])
handler_response(response)
port = "27042"
manager = frida.get_device_manager()
device = manager.add_remote_device(f"{phone_ip}:{port}")
logger_instance.info(f"[+] 已连接到远程设备: {phone_ip}:{port}")
try:
with open(SCRIPT_FILE, "r", encoding="utf-8") as f:
script_source = f.read()
logger_instance.info(f"[+] 成功加载脚本: {SCRIPT_FILE}")
except FileNotFoundError:
logger_instance.error(f"[-] 未找到脚本文件: {SCRIPT_FILE}")
logger_instance.error("[*] 请确保脚本文件在当前目录")
return
logger_instance.info(f"[+] 正在以重启方式启动小红书 ({PACKAGE_NAME}) 并注入脚本...")
try:
# 1. spawn 重启 App
pid = device.spawn([PACKAGE_NAME])
logger_instance.info(f"[+] App 已启动 (PID: {pid})")
# 2. attach 到新进程
session = device.attach(pid)
logger_instance.info("[+] 已附加到进程")
# print(script_source)
# 3. 创建并加载脚本
script = session.create_script(script_source)
script.on("message", on_message)
script.load()
logger_instance.info("[+] Hook 脚本注入成功!")
# 4. resume 让 App 继续运行
device.resume(pid)
logger_instance.info("[+] App 已恢复运行,请在小红书中触发搜索笔记操作")
logger_instance.info("[+] 响应数据会实时显示并保存到 xhs_search_notes.log")
# logger_instance.info("[+] 按 Ctrl+C 退出")
# 使用 uiautomator2 连接同一台手机(通过 ADB WiFi)
# d = u2.connect(f"{phone_ip}") # ADB WiFi 端口通常是 5555
# logger_instance.success(f"uiautomator2 已连接手机 {phone_ip}")
# # 保持进程运行(每个进程独立阻塞)
# while True:
# time.sleep(1)
# except frida.ProcessNotFoundError:
# print("[-] 进程未找到")
# except frida.InvalidArgumentError:
# print(f"[-] 包名错误,请确认是 {PACKAGE_NAME}")
# except KeyboardInterrupt:
# print("\n[+] 用户中断,正在退出...")
# except Exception as e:
# print(f"[-] 未知错误: {e}")
except Exception as e:
logger_instance.error(f"设备 {phone_ip} 错误: {e}")
time.sleep(10) # 出错等待后重试
@staticmethod
def start_frida(phone_ip, logger_instance):
"""
使用 Python 通过 ADB 在远程 Android 设备上启动 frida-server
相当于命令:
adb -s 172.200.5.98 shell "su -c 'setsid nohup /data/local/tmp/frida-server... &'"
"""
frida_server_path = "/data/local/tmp/frida-server-16.7.19-android-arm64"
# 构建完整的 shell 命令
cmd = [
"adb",
"-s", phone_ip,
"shell",
"su", "-c",
f"setsid nohup {frida_server_path} -l 0.0.0.0:{frida_port} > /dev/null 2>&1 &"
]
print(f"正在向 {phone_ip} 启动 frida-server(监听 {frida_port} 端口)...")
print("执行命令: " + " ".join(cmd))
try:
# 执行命令,捕获输出
result = subprocess.run(cmd, capture_output=True, text=True, timeout=30)
if result.returncode == 0:
print("命令发送成功!frida-server 已后台启动。")
else:
print("命令执行失败:")
print(result.stderr.strip())
return False
except subprocess.TimeoutExpired:
print("命令超时,通常表示已成功进入后台(正常现象)")
except Exception as e:
print(f"执行出错: {e}")
return False
# 等待几秒让 frida-server 完全启动
print("等待 5 秒让服务启动...")
time.sleep(5)
# 验证进程是否存活
def check_frida_running(device_ip):
"""检查 frida-server 进程是否在运行"""
try:
result = subprocess.run(
["adb", "-s", device_ip, "shell", "ps | grep frida-server"],
capture_output=True, text=True
)
if "frida-server" in result.stdout:
print("检测到 frida-server 进程正在运行:")
print(result.stdout.strip())
return True
else:
return False
except Exception as e:
print(f"检查进程时出错: {e}")
return False
if check_frida_running(phone_ip):
print(f"frida-server 启动成功!可通过 frida-ps -H {phone_ip}:{frida_port} 测试连接")
return True
else:
print("警告:未检测到 frida-server 进程,可能启动失败")
return False
@staticmethod
def start_proxy(phone_ip, logger_instance):
d = u2.connect(f"{phone_ip}")
@staticmethod
def unlock(phone_ip, logger_instance):
d = u2.connect(f"{phone_ip}")
if not d.info['screenOn']:
d.screen_on() # 或 d.press("power")
logger_instance.info("打开屏幕")
model = d.device_info["model"]
if model == "Pixel 3":
if d(resourceId="com.android.systemui:id/lock_icon").exists:
logger_instance("当前处于锁屏界面")
d.swipe(0.6, 0.85, 0.6, 0.2, 0.1)
time.sleep(1)
d.xpath('//*[@resource-id="com.android.systemui:id/key0"]').click()
d.xpath('//*[@resource-id="com.android.systemui:id/key3"]').click()
d.xpath('//*[@resource-id="com.android.systemui:id/key0"]').click()
d.xpath('//*[@resource-id="com.android.systemui:id/key4"]').click()
d.xpath('//*[@resource-id="com.android.systemui:id/key2"]').click()
d.xpath('//*[@resource-id="com.android.systemui:id/key8"]').click()
d.xpath('//*[@resource-id="com.android.systemui:id/key_enter"]').click()
else:
if d(resourceId="com.android.systemui:id/keyguard_indication_area").exists:
d.swipe(0.6, 0.85, 0.6, 0.2, 0.1)
@staticmethod
def connect_app(ip_port):
print(ip_port)
result = subprocess.run(['adb', 'connect', ip_port],
capture_output=True, text=True, timeout=10)
logger.success(f'{result.stdout, result.stderr}')
@staticmethod
def close_app(d):
d.app_stop("com.xingin.xhs")
def check_activity(d):
"""检查当前 activity,返回状态 key"""
info = d.app_current()
if info.get("package") == "com.xingin.xhs":
activity = info.get("activity")
return activity
# com.xingin.xhs
else:
logger.error("当前不在小红书中,连续执行几次返回键")
DeviceManager.close_app(d)
time.sleep(5)
logger.error(f"当前页面异常: {info}")
return "react"
def sleep_until_next_8am():
"""休眠直到次日 8 点"""
now = datetime.datetime.now()
tomorrow = now + datetime.timedelta(days=1)
next_8am = datetime.datetime(year=tomorrow.year, month=tomorrow.month, day=tomorrow.day, hour=8, minute=0, second=0)
seconds = (next_8am - now).total_seconds()
logger.success(f"需要休眠 {seconds / 3600:.2f} 小时,直到 {next_8am}")
time.sleep(seconds)
def dump_page(d, name):
"""保存页面 XML,用于调试"""
xml = d.dump_hierarchy()
if not name:
name = "./xml"
else:
name = "./" + name
with open(f'{name}.xml', 'w', encoding='utf-8') as f:
f.write(xml)
def format_seconds(seconds: int) -> str:
h = seconds // 3600
m = (seconds % 3600) // 60
s = seconds % 60
return f"{h}h{m}m{s}s"
def get_next_runtime(index: int):
"""计算下一次运行时长(带错峰)"""
base_runtime = random.randint(5400, 7200) # 1.5~2 小时
offset = index * 600 + random.randint(-300, 300) # 每台错开 10 分钟,再加小随机
return max(3600, base_runtime + offset)
def auto_operation(d, keyword, client_ip, logger_instance):
retry = 0
max_retry = 3
state_mgr = StateManager(client_ip)
while True:
try:
if state_mgr.check_status(d, client_ip):
if do_search_scroll(d, keyword, client_ip):
break
logger.error(f"{client_ip} 当前查询异常,重试关键词 {keyword}")
DeviceManager.start_app(client_ip, logger_instance)
continue
else:
set_device_status(client_ip, "0")
except TimeoutError as e:
retry += 1
logger.error(f"{keyword} 强恢复触发({retry}/{max_retry}):{e} -> 关闭 App 休息后继续")
DeviceManager.close_app(d)
sleep_time = random.randint(60, 120)
logger.success(f"休息 {sleep_time} 秒后继续当前关键词")
time.sleep(sleep_time)
DeviceManager.start_app(client_ip, logger_instance)
time.sleep(5)
if retry >= max_retry:
break
def set_device_status(client_ip, status):
common_redis0.hset("xhs_device_status", client_ip, status)
def xxx(timestamp):
dt = datetime.datetime.fromtimestamp(timestamp)
# 格式化为年月日
return dt.strftime("%Y%m%d")
def worker(client_ip, index):
# 每个进程独立 logger
logger_instance = setup_logger(client_ip)
logger_instance.info(f"进程 {index} 启动,负责手机 {client_ip}")
spider_task_count = 0
while 1:
try:
# DeviceManager.unlock(client_ip, logger_instance)
# DeviceManager.start_frida(client_ip, logger_instance)
# # DeviceManager.start_proxy()
# DeviceManager.start_app(ip, logger_instance)
"""每台手机独立进程"""
# 初始化信息
DeviceManager.connect_app(client_ip)
DeviceManager.start_frida(client_ip, logger_instance)
logger.success(client_ip)
d = u2.Device(client_ip)
DeviceManager.unlock(client_ip, logger_instance)
# current_app = d.app_current()
# print(f"当前前台应用: {current_app}")
# dump_page(d,"./te")
# return
DeviceManager.close_app(d)
time.sleep(5)
DeviceManager.start_app(client_ip, logger_instance)
time.sleep(10)
state_mgr = StateManager(client_ip)
# 初始状态检测 确认当前设备与帐号可用
if state_mgr.check_status(d, client_ip):
set_device_status(client_ip, "1")
# 初始化各种时间
base_runtime = random.randint(5400, 7200)
offset = index * 600 + random.randint(-300, 300)
rest_after = max(1800, base_runtime + offset) #
start_time = int(time.time())
while 1:
task = common_redis0.spop("xhs:keyword:package:m:ks")
if not task:
# logger.info(f"{device_ip} 当前暂无任务,休息 1s")
time.sleep(1)
continue
if "," in task or not task:
continue
logger.success(task)
if ":::" not in task:
continue
task, pt = task.split(":::")
status = common_redis0.sadd(f"xhs:keyword:package:m:ks:{xxx(time.time())}", task)
if status == 0:
logger.info(f"{task}今日已经完成采集")
continue
now = datetime.datetime.now()
# ---------- 夜间休眠逻辑 ----------
if 2 <= now.hour < 8:
DeviceManager.close_app(d)
tomorrow_8am = now.replace(hour=8, minute=0, second=0, microsecond=0)
if now.hour >= 8: # 万一跨天
tomorrow_8am += datetime.timedelta(days=1)
sleep_time = int((tomorrow_8am - now).total_seconds())
sleep_time += index * 300 + random.randint(-60, 60)
logger.success(f"{client_ip} 夜间休眠至早上8点,总休眠 {format_seconds(sleep_time)}")
time.sleep(sleep_time)
# 重新启动 app
spider_task_count = 0
rest_after = get_next_runtime(index)
start_time = int(time.time())
DeviceManager.start_app(client_ip, logger_instance)
time.sleep(5)
spider_task_count = 0
continue
# ---------- 白天运行逻辑 ----------
elapsed = int(time.time() - start_time)
if elapsed > rest_after:
DeviceManager.close_app(d)
sleep_time = random.randint(1200, 3600)
logger.success(f"{client_ip} 白天休息 {format_seconds(sleep_time)}")
time.sleep(sleep_time)
# 重置计时器
rest_after = get_next_runtime(index)
start_time = int(time.time())
DeviceManager.start_app(client_ip, logger_instance)
time.sleep(5)
# ---------- 采集量过大逻辑 ----------
if spider_task_count > 280:
logger.success(f"{client_ip} 当前搜索量大于280,立即结束今日采集并休眠到次日 8 点")
DeviceManager.close_app(d)
tomorrow_8am = now.replace(hour=8, minute=0, second=0, microsecond=0)
if now.hour >= 8:
tomorrow_8am += datetime.timedelta(days=1)
sleep_time = int((tomorrow_8am - now).total_seconds())
sleep_time += index * 300 + random.randint(-60, 60)
logger.success(f"{client_ip} 夜间休眠至早上8点,总休眠 {format_seconds(sleep_time)}")
time.sleep(sleep_time)
# 重置
spider_task_count = 0
rest_after = get_next_runtime(index)
start_time = int(time.time())
DeviceManager.start_app(client_ip, logger_instance)
# 正常操作
redis_conn3.hset(f"xhs_app:{client_ip}", task, '0')
redis_conn3.hset(f"xhs_app:{client_ip}:{task}", task, "1")
auto_operation(d, task, client_ip, logger_instance)
spider_task_count += 1
logger.info(f"{client_ip} {task} 已完成 任务总量 -> {spider_task_count}")
timeSleep = random.randint(3, 8)
time.sleep(timeSleep)
else:
logger.error(f"{client_ip} 当前设备无法使用 ")
continue
except KeyboardInterrupt:
logger_instance.info("进程被中断")
except Exception as e:
logger_instance.error(f"进程异常退出: {e}")
def main():
phone_num = len(search_clientip)
processes = []
for idx, ip in enumerate(search_clientip):
p = multiprocessing.Process(target=worker, args=(ip, idx), daemon=True) # ← 修改1:添加 daemon=True
p.start()
processes.append(p)
try:
for p in processes:
p.join()
except KeyboardInterrupt:
print("主进程收到中断信号,守护进程将自动退出...") # ← 修改2:捕获 Ctrl+C,确保主进程退出
if __name__ == '__main__':
main()
# start_frida_via_serial("b6f8967f")
\ No newline at end of file
import datetime
import multiprocessing
import random
import traceback
import requests
import uiautomator2 as u2
from redis import Redis
import re
import time
import pymysql
from pymysql.err import OperationalError
from loguru import logger
import frida
import sys
import json
# ===================== 全局配置 =====================
KEYCODE_MAP = {
"0": 7, "1": 8, "2": 9, "3": 10, "4": 11,
"5": 12, "6": 13, "7": 14, "8": 15, "9": 16
}
redis_conn3 = Redis(host="172.16.0.24", password="aiyingli@@123", db=3, decode_responses=True)
common_redis0 = Redis(host="172.16.0.24", password="aiyingli@@123", db=0, decode_responses=True)
redis_conn2 = Redis(host="172.16.0.24", password="aiyingli@@123", db=2, decode_responses=True)
SCRIPT_FILE = "hook_dlopen.js"
PACKAGE_NAME = "com.xingin.xhs"
from tools import client_account, user_clientip, client_proxy
import subprocess
FRIDA_SERVER_PATH = "/data/local/tmp/frida-server-16.7.19-android-arm64"
LOCAL_FRIDA_SERVER = "frida-server-16.7.19-android-arm64" # 本地文件路径,改成你的实际路径
search_clientip = [
# "172.200.2.179",
# "172.200.2.109",
# "172.200.2.210",
# "172.200.2.118",
# "172.200.2.74",
# "172.200.2.132",
# "172.200.2.83",
# "172.200.2.75",
# "172.200.2.126",
# "172.200.2.81",
# "172.200.2.70",
# "172.200.4.18",
# "172.200.4.126",
# "172.200.4.11",
# # "172.200.2.196",
# "18910081473": "http://iprowq:yk2gbxo4@111.170.157.180:16816",
# "172.200.4.115",
# "18911415293": "http://iprowq:yk2gbxo4@42.51.0.234:16816",
# "172.200.4.155",
# "172.200.4.13",
# "18911482557": "http://iprowq:yk2gbxo4@117.50.201.181:16816",
# "172.200.5.70",
# "18911475707": "http://iprowq:yk2gbxo4@36.134.120.81:16816",
# "172.200.5.98",
# "18911461625": "http://iprowq:yk2gbxo4@42.51.42.254:16818",
# "172.200.4.6",
# "172.200.4.18",
# "172.200.4.37",
# "172.200.4.13"
# "172.200.4.16",
# "172.200.4.43",
# "172.200.4.26",
"172.200.4.38",
"172.200.5.0",
"172.200.4.252",
"172.200.4.214",
"172.200.4.23",
"172.200.4.24",
"172.200.4.31",
"172.200.4.39",
]
wait_set_phone = [
"172.200.4.155",
"172.200.5.98",
"172.200.5.99",
"172.200.5.70"
]
frida_port = "27042"
def setup_logger(ip):
"""为每台手机创建独立的日志文件"""
log_file = f"xhs_log_{ip.replace('.', '_')}.log"
# 移除默认 logger,添加文件输出
logger.remove() # 移除默认 stdout
# logger.add(log_file, rotation="10 MB", retention="7 days", encoding="utf-8")
logger.add(sys.stderr, level="INFO") # 保留终端关键输出
return logger
class SimpleMySQL:
"""极简查询封装:只支持 SELECT * … WHERE ..."""
def __init__(self, charset="utf8mb4"):
self.cfg = dict(host="tenant-2101894307-cn-beijing-public.bytehouse.volces.com", port=3306, user="bytehouse",
password="m1wUyPHX0H:JQDqesXaoc", db="douchacha_data", charset=charset,
cursorclass=pymysql.cursors.DictCursor,
autocommit=True
)
self._conn = None
self._connect()
# ---------- public ----------
def query(self, phone_num, start_time, deadline):
sql = f"SELECT * FROM recv_sms WHERE phone_num = {phone_num} AND recv_time >= {start_time} AND recv_time <= {deadline}"
try:
return self._execute(sql)
except OperationalError as e: # 连接异常自动重连一次
print(e)
if e.args and e.args[0] in (2006, 2013):
self._reconnect()
return self._execute(sql)
raise
# ---------- private ----------
def _connect(self):
if self._conn:
self._conn.close()
self._conn = pymysql.connect(**self.cfg)
def _reconnect(self):
try:
self._connect()
except Exception as e:
raise RuntimeError(f"Reconnect failed: {e}") from e
def _execute(self, sql):
with self._conn.cursor() as cur:
cur.execute(sql)
return cur.fetchall()
def close(self):
self._conn.close()
def _ensure_conn(self):
try:
self._conn.ping(reconnect=True) # 如果断了会自动重连
except Exception as e:
logger.error(f"MySQL ping failed, reconnecting: {e}")
self._conn = self._connect() # 你自己封装的重连逻辑
def replace_into(self, table, item_list):
self._ensure_conn()
if not item_list:
return 0
try:
keys = list(item_list[0].keys())
cols = ", ".join(f"`{k}`" for k in keys)
placeholders = ", ".join(["%s"] * len(keys))
sql = f"REPLACE INTO `{table}` ({cols}) VALUES ({placeholders})"
# 处理特殊字符
def sanitize_value(value):
if value is None:
return None
if isinstance(value, str):
# 移除或转义可能引起问题的字符
return value.replace('`', '').replace('\\', '\\\\')
return value
values = [tuple(sanitize_value(item[k]) for k in keys) for item in item_list]
try:
# 🔑 关键:写之前先 ping 一下,断了就重连
self._conn.ping(reconnect=True)
with self._conn.cursor() as cur:
cur.executemany(sql, values)
# self._conn.commit()
logger.success(f"********** {table} 共写入{len(item_list)}条数据 **********")
return len(values)
except Exception as e:
logger.error(f"MySQL 执行错误: {e}")
raise
except Exception as e:
print(f"Error: {e}")
self._connect()
db = SimpleMySQL()
def alert(msg):
url = "https://open.feishu.cn/open-apis/bot/v2/hook/1ac7eee2-1c29-477f-95f1-8f3f7df4a0b7"
payload = {
"msg_type": "text",
"content": {
"text": msg
}
}
try:
resp = requests.post(
url,
json=payload,
headers={"Content-Type": "application/json"},
timeout=10
)
resp.raise_for_status()
logger.info("Feishu alert sent, status=%s", resp.status_code)
except requests.RequestException as e:
logger.error("Feishu alert failed: %s", e)
class Login():
def __init__(self, client_ip):
self.client_ip = client_ip
def login(self, d, client_ip):
while 1:
page_activity = check_activity(d)
logger.success(page_activity)
if page_activity == "com.xingin.login.activity.WelcomeActivity":
# 微信登陆界面
dump_page(d, "WelcomeActivity")
if d(text="一键登录"):
logger.success("开始使用一键登录")
d.xpath('//android.widget.LinearLayout/android.widget.Button[@index="0"]').click()
time.sleep(2)
d(text="一键登录").click()
time.sleep(3)
if d(text='同意并继续'):
d(text="同意并继续").click()
time.sleep(2)
elif d(text="手机号登录").exists:
logger.success("找到使用手机号登录,开始点击操作")
d(text="手机号登录").click()
time.sleep(3)
else:
logger.error("未找到手机号登录选项,需要单独处理")
elif page_activity == "com.xingin.login.halfwelcome.HalfWelcomeActivity":
# 当前页面仅有手机号登陆
dump_page(d, "HalfWelcomeActivity")
if d(text="手机号登录").exists:
logger.success("找到手机号登录,开始点击操作")
d(text="手机号登录").click()
time.sleep(3)
else:
logger.error("未找到手机号登录选项,需要单独处理")
elif page_activity == "com.xingin.login.activity.LoginActivity":
# 手机号登陆界面
# dump_page(d,"LoginActivity")
# logger.success("写入完成")
# exit()
# time.sleep(3)
if d(description="全部删除").exists:
try:
phone_number = d(textMatches="\\d{3} \\d{4} \\d{4}").get_text()
logger.success(f"当前手机号为{phone_number}")
except:
phone_number = ""
if phone_number != "":
logger.error("直接发送短信")
logger.success("找到 全部删除 开始点击")
d(description="全部删除").click()
time.sleep(2)
el = d.xpath('//android.widget.EditText[@hint="请输入手机号码"]')
if el:
el.click()
phone = client_account[client_ip]
for char in phone:
d.send_keys(char)
time.sleep(0.1)
else:
logger.error("没有找到 el")
d(description="未选中,同意").click()
time.sleep(1)
# 4. 点击 "验证并登录"
d(text="验证并登录").click()
time.sleep(1)
account = client_account[client_ip]
code = ""
for attempt in range(1, 4):
if attempt != 1:
d(text="重新发送").click()
time.sleep(2)
logger.info(f"=== 第 {attempt} 次尝试登陆 {account} ===")
start_time = int(time.time())
deadline = start_time + 60
while time.time() < deadline:
rows = db.query(account, start_time, deadline)
if rows:
msg = rows[0]["msg"]
code = re.search(r"\b(\d{4,6})\b", msg).group(1)
break
time.sleep(3)
if not code:
logger.warning(f"{account} 第 {attempt} 次未获取到验证码,准备重试")
continue
# if attempt == MAX_RETRY:
break
if code == "":
return
logger.success(f"{account} 获取验证码成功:{code}")
d(text="输入验证码").click()
time.sleep(1)
for char in code:
d.send_keys(char)
time.sleep(0.1)
d(text="登录").click()
time.sleep(3)
elif page_activity == "com.xingin.login.device.offline.DeviceOfflineRemindActivity":
if d(text="账号下线提示"):
logger.error("当前弹窗登录掉线,点击重新登录")
d(text="重新登录").click()
time.sleep(3)
continue
elif page_activity == "com.xingin.reactnative.ui.WalifyReactTranslucentActivity":
logger.error("当前设备验证异常")
alert(f"小红书检测设备 {client_ip} 登陆异常,请及时查看")
set_device_status(client_ip, "0")
return
elif page_activity == "com.xingin.alioth.search.GlobalSearchActivity":
return
def check_page_status(d, client_ip):
status_count = 0
while 1:
if d(text="网络好像断了,请检查手机是否联网").exists:
status_count += 1
if status_count == 5:
logger.error("连续点击*重新加载*异常 退出当前词查询 发送报警")
return False
logger.error(f'{client_ip} 网络异常 重新等待五秒后重新点击搜索')
time.sleep(3)
if d(text="重新加载").exists:
logger.error(f"{client_ip} 当前有重新加载按钮 点击重新加载")
d(text="重新加载").click()
time.sleep(2)
continue
elif d(text="搜索").exists:
logger.error("当前网络连接异常 未找到重新加载按钮,重新点击搜索")
d(text="搜索").click()
time.sleep(2)
continue
return True
def human_like_scroll(d, keyword, client_ip, max_up=2, min_delay=2.0, max_delay=4.0):
screen_width, screen_height = d.window_size()
up_count = 0
down_count = 0
continuous_down = 0 # 连续下滑计数
random_down_threshold = random.randint(3, 5) # 触发上滑的门槛(3~5 次下滑后才允许上滑)
last_spider_count = None
last_change_time = time.time()
start_time = time.time()
max_nochange_time = 1000
last_progress_time = time.time() # 只在 spider_count 变动时更新,用于 5 分钟强恢复
while True:
try:
# TODO: 退出条件 -> redis hget(f"xhs_app:{client_ip}:{keyword}", keyword) == 5 时 break
if not check_page_status(d, client_ip):
return False
if d(text="无更多内容").exists:
logger.success("采集完成 无更多内容")
return True
elif d(text="没有找到相关内容,换个词试试吧").exists:
logger.success("没有找到相关内容,换个词试试吧")
return True
try:
spider_count = redis_conn3.hget(f"xhs_app:{client_ip}", keyword)
# logger.success(f"xhs_app:{client_ip} keyword -> {keyword} spider_count -> {spider_count}", )
if spider_count is not None:
spider_count = int(spider_count)
except Exception as e:
print(f"[Redis异常] {e}")
spider_count = None
if spider_count == 5:
# logger.success(f"{keyword} 当前已拦截5次 退出滑动")
return True
if spider_count is not None:
if spider_count != last_spider_count:
# 正常进度,更新记录
last_spider_count = spider_count
last_change_time = time.time()
else:
# 计数没变化,超过15s → 认为卡住
if time.time() - last_change_time > 200:
# print("[卡顿检测] 页面长时间无变化,触发多次上滑+强力下滑容错")
# 连续上滑 2~3 次
for _ in range(random.randint(2, 3)):
d.swipe(
screen_width // 2,
int(screen_height * 0.6),
screen_width // 2,
int(screen_height * 0.8),
0.3
)
time.sleep(0.8)
# 强力下滑(90% 屏幕高度)
d.swipe(
screen_width // 2,
int(screen_height * 0.9),
screen_width // 2,
int(screen_height * 0.1),
0.5
)
time.sleep(3)
# 重置检测计时器
last_change_time = time.time() # 默认方向下滑
if time.time() - last_progress_time > max_nochange_time:
return False
# raise TimeoutError("spider_count 长时间无变化,触发强恢复")
direction = "down"
# 控制上滑逻辑:必须连续下滑 >= 随机门槛,且上滑次数不能超过 max_up
if continuous_down >= random_down_threshold and up_count < max_up and random.random() < 0.2:
direction = "up"
up_count += 1
continuous_down = 0 # 重置连续下滑计数
random_down_threshold = random.randint(3, 5) # 重新生成门槛
else:
direction = "down"
down_count += 1
continuous_down += 1
# ---- 改进的滑动区域计算(基于屏幕中间) ----
start_x = int(screen_width * 0.5 + random.randint(-50, 50)) # 中间 ±50px
start_y = int(screen_height * (0.5 + random.uniform(-0.2, 0.2))) # 中间 ±20% 高度
if direction == "down":
move_distance = int(screen_height * random.uniform(0.5, 0.7)) # 下滑距离 50%~70%
end_y = start_y - move_distance
else:
move_distance = int(screen_height * random.uniform(0.3, 0.5)) # 上滑保持中等力度
end_y = start_y + move_distance
# 边界保护,避免滑到最顶/最底
end_y = max(100, min(screen_height - 100, end_y))
duration = float(random.uniform(0.15, 0.3)) # 更快的滑动
# 执行滑动
try:
d.swipe(start_x, start_y, start_x, end_y, duration)
except Exception as e:
print(f"[滑动异常] {e}")
# 兜底强制下滑一次,避免卡死
d.swipe(screen_width // 2, int(screen_height * 0.8), screen_width // 2, int(screen_height * 0.2), 0.3)
continue
# 模拟浏览(拟人化操作)
action_chance = random.random()
if action_chance < 0.2:
# 偶尔长时间停留(认真看内容)
delay = random.uniform(5, 8)
# logger.info(f"[拟人操作] 长时间停留 {delay:.1f}s 模拟认真看内容")
time.sleep(delay)
elif action_chance < 0.3:
# 偶尔小幅度微调滑动
offset = random.randint(50, 120)
d.swipe(start_x, start_y, start_x, start_y - offset, random.uniform(0.1, 0.2))
time.sleep(random.uniform(1, 2))
elif action_chance < 0.4:
# 偶尔什么都不做,模拟发呆
delay = random.uniform(1, 3)
# logger.info(f"[拟人操作] 发呆中 {delay:.1f}s")
time.sleep(delay)
else:
# 正常停顿浏览(快速翻页)
delay = random.uniform(1, 2.0)
time.sleep(delay)
except Exception as e:
logger.error(e)
continue
def phone_operation(d, command):
d.press(command)
def do_search_scroll(d, task, client_ip):
try:
if d(description="全部删除").exists:
d(description="全部删除").click()
logger.success("清空上次搜索内容")
if d(text="搜索, ").exists:
d(text="搜索, ").click()
for char in task:
d.send_keys(char)
time.sleep(random.uniform(0.1, 0.3))
if random.random() < 0.05:
d.send_keys(random.choice("abcdefghijklmnopqrstuvwxyz"))
time.sleep(0.1)
d.press("delete")
time.sleep(0.1)
d(text="搜索").click()
time.sleep(3)
if human_like_scroll(d, task, client_ip):
logger.info(client_ip + "操作成功")
return True
logger.error("操作失敗")
return False
else:
dump_page(d, "")
logger.success("没有找到当前按钮")
except Exception as e:
traceback.print_exc()
logger.error(e)
class StateManager:
# 当前手机状态管理 检测账号是否异常,当前函数结束时候 需要将手机保持在 搜索页面中GlobalSearchActivity
def __init__(self, client_ip):
self.client_ip = client_ip
def check_status(self, d, client_ip):
def handler_security_ui(info):
if info.get("package") == "com.lbe.security.miui":
d(resourceId="com.lbe.security.miui:id/permission_deny_button").click()
time.sleep(2)
"""检查 frida-server 进程是否在运行"""
try:
result = subprocess.run(
["adb", "-s", client_ip, "shell", "ps | grep frida-server"],
capture_output=True, text=True
)
if "frida-server" in result.stdout:
print("检测到 frida-server 进程正在运行:")
print(result.stdout.strip())
else:
return False
except Exception as e:
print(f"检查进程时出错: {e}")
return False
d.app_start("cn.ys1231.appproxy", ".MainActivity")
current = d.app_current()
if current["package"] == "cn.ys1231.appproxy" and current["activity"] == ".MainActivity":
logger.info(current)
switch = d(descriptionContains="http ")
if switch and switch.info.get("className") == "android.widget.Switch":
while True:
if not switch.info["checked"]:
switch.click()
time.sleep(2)
else:
break
recent_app = d(resourceId="com.android.systemui:id/recent_apps")
recent_app.click()
time.sleep(1)
xhs_app_card = d(description="小红书,未加锁")
xhs_app_card.click()
time.sleep(1)
info = d.app_current()
if info.get("package") == "com.xingin.xhs":
while 1:
info = d.app_current()
logger.warning(info)
activity = info.get("activity")
logger.success(f"{client_ip},{activity}")
DeviceManager.unlock(client_ip, logger)
if activity == "com.xingin.alioth.search.GlobalSearchActivity":
if d(text="服务器迷路了,晚点再试试吧").exists:
logger.error(f"{client_ip} 服务器迷路了,晚点再试试吧")
common_redis0.hset("xhs_device_status", client_ip, "0")
time.sleep(240)
continue
common_redis0.hset("xhs_device_status", client_ip, "1")
return True
elif activity in [".index.v2.IndexActivityV2", "com.xingin.xhs.index.v2.IndexActivityV2"]:
logger.success("当前手机页面处于首页,检测是否需要登陆,不需要登陆则跳转到搜索页面")
if d(text="登录发现更多精彩").exists and d(text="去登录").exists:
logger.error("当前账号掉线 重新登陆")
d(text="去登录").click()
Login(self.client_ip).login(d, client_ip)
elif d(text="账号下线提示"):
logger.error("当前弹窗登录掉线,点击重新登录")
d(text="重新登录").click()
time.sleep(3)
continue
else:
logger.success("当前无需登录,跳转到搜索页面")
if d(description="搜索").exists:
d(description="搜索").click()
time.sleep(3)
continue
elif activity in ["com.xingin.login.activity.WelcomeActivity",
"com.xingin.login.activity.LoginActivity",
"com.xingin.login.device.offline.DeviceOfflineRemindActivity",
"com.xingin.login.halfwelcome.HalfWelcomeActivity"]:
logger.success("当前正在登陆页面中,直接执行登陆程序")
Login(self.client_ip).login(d, client_ip)
elif activity == "com.xingin.reactnative.ui.WalifyReactTranslucentActivity":
logger.error("当前设备验证异常")
if d(text="当前账户异常, 允许启用本地生物验证").exists:
alert(f"小红书检测设备 {client_ip} 登陆异常 状态:当前账户异常, 允许启用本地生物验证,请及时查看")
else:
alert(f"小红书检测设备 {client_ip} 登陆异常 状态:未知状态,请及时查看")
common_redis0.hset("xhs_device_status", client_ip, "0")
return False
elif activity == "com.xingin.matrix.notedetail.NoteDetailActivity":
logger.warning(f"当前进入卡片详情页,点击退出当前页面")
d.click(44, 164)
time.sleep(3)
else:
logger.error(f"当前Activity 未处理:{activity}")
time.sleep(40)
while 1:
info = d.app_current()
logger.error(f'当前页面不在小红书中:{info.get("package")}')
for i in range(5):
phone_operation(d, 'back')
time.sleep(1)
DeviceManager.start_app(client_ip, logger)
time.sleep(5)
if info.get("package") == "com.xingin.xhs":
break
else:
logger.error(f"打开小红书失败,重新尝试,当前页面为:{info.get('package')}")
time.sleep(10)
handler_security_ui(info)
continue
else:
while 1:
info = d.app_current()
logger.error(f'当前页面不在小红书中:{info.get("package")}')
for i in range(5):
phone_operation(d, 'back')
time.sleep(1)
DeviceManager.start_app(client_ip, logger)
time.sleep(5)
if info.get("package") == "com.xingin.xhs":
break
else:
logger.error(f"打开小红书失败,重新尝试,当前页面为:{info.get('package')}")
time.sleep(10)
handler_security_ui(info)
continue
def check_collection_status(self, d):
client_status = redis_conn3.hget(f"xhs_app:status:{self.client_ip}", 'status')
if client_status == "infinity":
logger.success(f"{self.client_ip} 当前已经搜索超过上限,关闭系统等待明日采集")
DeviceManager.close_app(d)
sleep_until_next_8am()
logger.success(f"{self.client_ip} 当前完成休眠,开始继续运行")
redis_conn3.hset(f"xhs_app:status:{self.client_ip}", 'status', "success")
return False
return True
class DeviceManager:
@staticmethod
def start_app(phone_ip, logger_instance):
db = SimpleMySQL()
redis_conn = Redis(host="172.16.0.24", password="aiyingli@@123", db=3, decode_responses=True)
redis_conn2 = Redis(host="172.16.0.24", password="aiyingli@@123", db=2, decode_responses=True)
keyword_count = {}
# 重启应用的时候查看ip
d = u2.connect(f"{phone_ip}")
d.app_start("cn.ys1231.appproxy", ".MainActivity")
current = d.app_current()
switch = d(descriptionContains="http ")
if switch and switch.info.get("className") == "android.widget.Switch":
while True:
if not switch.info["checked"]:
switch.click()
time.sleep(2)
else:
logger.info("代理已开启")
break
# try:
# device = frida.get_usb_device(timeout=10,)
# print(f"[+] 已连接到设备: {device}")
# except Exception as e:
# print(f"[-] 无法连接设备: {e}")
# return
# 1. 添加远程设备(WiFi 连接)
# phone_ip = "172.200.4.115"
def handler_response(response):
try:
# logger_instance.info(response.get("url"))
# logger_instance.info(response.get("status"))
from urllib.parse import urlparse, parse_qs, parse_qsl
url = response.get("url")
# 解析 URL
parsed_url = urlparse(url)
query_params = parse_qs(parsed_url.query)
keyword = query_params["keyword"][0]
if keyword in keyword_count:
keyword_count[keyword] += 1
else:
keyword_count[keyword] = 1
count = keyword_count[keyword]
redis_conn.hset(f"xhs_app:{phone_ip}", keyword, count)
try:
response_data = json.loads(response.get("response_body"))
if response_data.get("data", {}):
items = response_data.get("data", {}).get("items", [])
if len(items) > 0:
item_list = []
for idx, item in enumerate(items):
model_type = item.get("model_type")
if model_type == "dsl" or model_type == "hot_query" or model_type == "questionnaire_survey" or model_type == "ads":
continue
try:
global_rank = (count - 1) * 20 + idx + 1
data_dic = {}
data_dic["key_word"] = keyword
data_dic["rank"] = global_rank
data_dic["video_id"] = item.get("note").get("id")
data_dic["update_pt"] = xxx(time.time()) + "00"
data_dic["create_pt"] = xxx(time.time())
item_list.append(data_dic)
except:
# logger.error(item.get("note"))
logger.success(f"{model_type} {item}")
# logger_instance.info(item_list)
db.replace_into("ods_aidso_monitor_video_rank_xhs", item_list)
# logger.success(items)
logger_instance.success(f"[{phone_ip}]:{keyword} 拦截成功 len -> {len(items)}")
else:
logger_instance.success(f"{keyword} 拦截失败")
redis_conn.hset(f"xhs_app:{phone_ip}:{keyword}", keyword, "1")
else:
logger_instance.info(response_data)
if response_data.get('msg') == "访问次数已达上限,请改天再试":
redis_conn.hset(f"xhs_app:status:{phone_ip}", "status", "infinity")
# if response_data.get("code") == 300013:
# logger.error(flow.response.json())
# if response_data.get("code") == -100:
print("获取data失败咯")
except Exception as e:
logger.error(f"解析 response 失败: {e}")
# logger.info(flow.response.text)
if keyword != '':
redis_conn.hset(f"xhs_app:{phone_ip}:{keyword}", keyword, "0")
if count == 5:
del keyword_count[keyword]
logger_instance.info(f"{phone_ip} {keyword} 达到5次, 已从 缓存 删除")
except Exception as e:
logger.error("失败")
def on_message(message, data):
"""
Frida 脚本通过 send() 发送的消息会在这里接收
如果脚本只用 console.log(),会作为 'log' 类型进来
"""
if message['type'] == 'send':
# print("[*] {0}".format(message['payload']))
response = json.loads(message['payload'])
handler_response(response)
port = "27042"
manager = frida.get_device_manager()
device = manager.add_remote_device(f"{phone_ip}:{port}")
logger_instance.info(f"[+] 已连接到远程设备: {phone_ip}:{port}")
try:
with open(SCRIPT_FILE, "r", encoding="utf-8") as f:
script_source = f.read()
logger_instance.info(f"[+] 成功加载脚本: {SCRIPT_FILE}")
except FileNotFoundError:
logger_instance.error(f"[-] 未找到脚本文件: {SCRIPT_FILE}")
logger_instance.error("[*] 请确保脚本文件在当前目录")
return
logger_instance.info(f"[+] 正在以重启方式启动小红书 ({PACKAGE_NAME}) 并注入脚本...")
try:
# 1. spawn 重启 App
pid = device.spawn([PACKAGE_NAME])
logger_instance.info(f"[+] App 已启动 (PID: {pid})")
# 2. attach 到新进程
session = device.attach(pid)
logger_instance.info("[+] 已附加到进程")
# print(script_source)
# 3. 创建并加载脚本
script = session.create_script(script_source)
script.on("message", on_message)
script.load()
logger_instance.info("[+] Hook 脚本注入成功!")
# 4. resume 让 App 继续运行
device.resume(pid)
logger_instance.info("[+] App 已恢复运行,请在小红书中触发搜索笔记操作")
logger_instance.info("[+] 响应数据会实时显示并保存到 xhs_search_notes.log")
# logger_instance.info("[+] 按 Ctrl+C 退出")
# 使用 uiautomator2 连接同一台手机(通过 ADB WiFi)
# d = u2.connect(f"{phone_ip}") # ADB WiFi 端口通常是 5555
# logger_instance.success(f"uiautomator2 已连接手机 {phone_ip}")
# # 保持进程运行(每个进程独立阻塞)
# while True:
# time.sleep(1)
# except frida.ProcessNotFoundError:
# print("[-] 进程未找到")
# except frida.InvalidArgumentError:
# print(f"[-] 包名错误,请确认是 {PACKAGE_NAME}")
# except KeyboardInterrupt:
# print("\n[+] 用户中断,正在退出...")
# except Exception as e:
# print(f"[-] 未知错误: {e}")
except Exception as e:
logger_instance.error(f"设备 {phone_ip} 错误: {e}")
time.sleep(10) # 出错等待后重试
@staticmethod
def start_frida(phone_ip, logger_instance):
"""
使用 Python 通过 ADB 在远程 Android 设备上启动 frida-server
相当于命令:
adb -s 172.200.5.98 shell "su -c 'setsid nohup /data/local/tmp/frida-server... &'"
"""
frida_server_path = "/data/local/tmp/frida-server-16.7.19-android-arm64"
# 构建完整的 shell 命令
cmd = [
"adb",
"-s", phone_ip,
"shell",
"su", "-c",
f"setsid nohup {frida_server_path} -l 0.0.0.0:{frida_port} > /dev/null 2>&1 &"
]
print(f"正在向 {phone_ip} 启动 frida-server(监听 {frida_port} 端口)...")
print("执行命令: " + " ".join(cmd))
try:
# 执行命令,捕获输出
result = subprocess.run(cmd, capture_output=True, text=True, timeout=30)
if result.returncode == 0:
print("命令发送成功!frida-server 已后台启动。")
else:
print("命令执行失败:")
print(result.stderr.strip())
return False
except subprocess.TimeoutExpired:
print("命令超时,通常表示已成功进入后台(正常现象)")
except Exception as e:
print(f"执行出错: {e}")
return False
# 等待几秒让 frida-server 完全启动
print("等待 5 秒让服务启动...")
time.sleep(5)
# 验证进程是否存活
def check_frida_running(device_ip):
"""检查 frida-server 进程是否在运行"""
try:
result = subprocess.run(
["adb", "-s", device_ip, "shell", "ps | grep frida-server"],
capture_output=True, text=True
)
if "frida-server" in result.stdout:
print("检测到 frida-server 进程正在运行:")
print(result.stdout.strip())
return True
else:
return False
except Exception as e:
print(f"检查进程时出错: {e}")
return False
if check_frida_running(phone_ip):
print(f"frida-server 启动成功!可通过 frida-ps -H {phone_ip}:{frida_port} 测试连接")
return True
else:
print("警告:未检测到 frida-server 进程,可能启动失败")
return False
@staticmethod
def start_proxy(phone_ip, logger_instance):
d = u2.connect(f"{phone_ip}")
@staticmethod
def unlock(phone_ip, logger_instance):
d = u2.connect(f"{phone_ip}")
if not d.info['screenOn']:
d.screen_on() # 或 d.press("power")
logger_instance.info("打开屏幕")
model = d.device_info["model"]
if model == "Pixel 3":
if d(resourceId="com.android.systemui:id/lock_icon").exists:
logger_instance("当前处于锁屏界面")
d.swipe(0.6, 0.85, 0.6, 0.2, 0.1)
time.sleep(1)
d.xpath('//*[@resource-id="com.android.systemui:id/key0"]').click()
d.xpath('//*[@resource-id="com.android.systemui:id/key3"]').click()
d.xpath('//*[@resource-id="com.android.systemui:id/key0"]').click()
d.xpath('//*[@resource-id="com.android.systemui:id/key4"]').click()
d.xpath('//*[@resource-id="com.android.systemui:id/key2"]').click()
d.xpath('//*[@resource-id="com.android.systemui:id/key8"]').click()
d.xpath('//*[@resource-id="com.android.systemui:id/key_enter"]').click()
else:
if d(resourceId="com.android.systemui:id/keyguard_indication_area").exists:
d.swipe(0.6, 0.85, 0.6, 0.2, 0.1)
@staticmethod
def connect_app(ip_port):
print(ip_port)
result = subprocess.run(['adb', 'connect', ip_port],
capture_output=True, text=True, timeout=10)
logger.success(f'{result.stdout, result.stderr}')
@staticmethod
def close_app(d):
d.app_stop("com.xingin.xhs")
def check_activity(d):
"""检查当前 activity,返回状态 key"""
info = d.app_current()
if info.get("package") == "com.xingin.xhs":
activity = info.get("activity")
return activity
# com.xingin.xhs
else:
logger.error("当前不在小红书中,连续执行几次返回键")
DeviceManager.close_app(d)
time.sleep(5)
logger.error(f"当前页面异常: {info}")
return "react"
def sleep_until_next_8am():
"""休眠直到次日 8 点"""
now = datetime.datetime.now()
tomorrow = now + datetime.timedelta(days=1)
next_8am = datetime.datetime(year=tomorrow.year, month=tomorrow.month, day=tomorrow.day, hour=8, minute=0, second=0)
seconds = (next_8am - now).total_seconds()
logger.success(f"需要休眠 {seconds / 3600:.2f} 小时,直到 {next_8am}")
time.sleep(seconds)
def dump_page(d, name):
"""保存页面 XML,用于调试"""
xml = d.dump_hierarchy()
if not name:
name = "./xml"
else:
name = "./" + name
with open(f'{name}.xml', 'w', encoding='utf-8') as f:
f.write(xml)
def format_seconds(seconds: int) -> str:
h = seconds // 3600
m = (seconds % 3600) // 60
s = seconds % 60
return f"{h}h{m}m{s}s"
def get_next_runtime(index: int):
"""计算下一次运行时长(带错峰)"""
base_runtime = random.randint(5400, 7200) # 1.5~2 小时
offset = index * 600 + random.randint(-300, 300) # 每台错开 10 分钟,再加小随机
return max(3600, base_runtime + offset)
def auto_operation(d, keyword, client_ip, logger_instance):
retry = 0
max_retry = 3
state_mgr = StateManager(client_ip)
while True:
try:
if state_mgr.check_status(d, client_ip):
if do_search_scroll(d, keyword, client_ip):
break
logger.error(f"{client_ip} 当前查询异常,重试关键词 {keyword}")
DeviceManager.start_app(client_ip, logger_instance)
continue
else:
set_device_status(client_ip, "0")
except TimeoutError as e:
retry += 1
logger.error(f"{keyword} 强恢复触发({retry}/{max_retry}):{e} -> 关闭 App 休息后继续")
DeviceManager.close_app(d)
sleep_time = random.randint(60, 120)
logger.success(f"休息 {sleep_time} 秒后继续当前关键词")
time.sleep(sleep_time)
DeviceManager.start_app(client_ip, logger_instance)
time.sleep(5)
if retry >= max_retry:
break
def set_device_status(client_ip, status):
common_redis0.hset("xhs_device_status", client_ip, status)
def xxx(timestamp):
dt = datetime.datetime.fromtimestamp(timestamp)
# 格式化为年月日
return dt.strftime("%Y%m%d")
def worker(client_ip, index):
# 每个进程独立 logger
logger_instance = setup_logger(client_ip)
logger_instance.info(f"进程 {index} 启动,负责手机 {client_ip}")
spider_task_count = 0
while 1:
try:
# DeviceManager.unlock(client_ip, logger_instance)
# DeviceManager.start_frida(client_ip, logger_instance)
# # DeviceManager.start_proxy()
# DeviceManager.start_app(ip, logger_instance)
"""每台手机独立进程"""
# 初始化信息
DeviceManager.connect_app(client_ip)
DeviceManager.start_frida(client_ip, logger_instance)
logger.success(client_ip)
d = u2.Device(client_ip)
DeviceManager.unlock(client_ip, logger_instance)
# current_app = d.app_current()
# print(f"当前前台应用: {current_app}")
# dump_page(d,"./te")
# return
DeviceManager.close_app(d)
time.sleep(5)
DeviceManager.start_app(client_ip, logger_instance)
time.sleep(10)
state_mgr = StateManager(client_ip)
# 初始状态检测 确认当前设备与帐号可用
if state_mgr.check_status(d, client_ip):
set_device_status(client_ip, "1")
# 初始化各种时间
base_runtime = random.randint(5400, 7200)
offset = index * 600 + random.randint(-300, 300)
rest_after = max(1800, base_runtime + offset) #
start_time = int(time.time())
while 1:
task = common_redis0.spop("xhs:keyword:package:m:ks")
if not task:
# logger.info(f"{device_ip} 当前暂无任务,休息 1s")
time.sleep(1)
continue
if "," in task or not task:
continue
logger.success(task)
if ":::" not in task:
continue
task, pt = task.split(":::")
status = common_redis0.sadd(f"xhs:keyword:package:m:ks:{xxx(time.time())}", task)
if status == 0:
logger.info(f"{task}今日已经完成采集")
continue
now = datetime.datetime.now()
# ---------- 夜间休眠逻辑 ----------
if 2 <= now.hour < 8:
DeviceManager.close_app(d)
tomorrow_8am = now.replace(hour=8, minute=0, second=0, microsecond=0)
if now.hour >= 8: # 万一跨天
tomorrow_8am += datetime.timedelta(days=1)
sleep_time = int((tomorrow_8am - now).total_seconds())
sleep_time += index * 300 + random.randint(-60, 60)
logger.success(f"{client_ip} 夜间休眠至早上8点,总休眠 {format_seconds(sleep_time)}")
time.sleep(sleep_time)
# 重新启动 app
spider_task_count = 0
rest_after = get_next_runtime(index)
start_time = int(time.time())
DeviceManager.start_app(client_ip, logger_instance)
time.sleep(5)
spider_task_count = 0
continue
# ---------- 白天运行逻辑 ----------
elapsed = int(time.time() - start_time)
if elapsed > rest_after:
DeviceManager.close_app(d)
sleep_time = random.randint(1200, 3600)
logger.success(f"{client_ip} 白天休息 {format_seconds(sleep_time)}")
time.sleep(sleep_time)
# 重置计时器
rest_after = get_next_runtime(index)
start_time = int(time.time())
DeviceManager.start_app(client_ip, logger_instance)
time.sleep(5)
# ---------- 采集量过大逻辑 ----------
if spider_task_count > 280:
logger.success(f"{client_ip} 当前搜索量大于280,立即结束今日采集并休眠到次日 8 点")
DeviceManager.close_app(d)
tomorrow_8am = now.replace(hour=8, minute=0, second=0, microsecond=0)
if now.hour >= 8:
tomorrow_8am += datetime.timedelta(days=1)
sleep_time = int((tomorrow_8am - now).total_seconds())
sleep_time += index * 300 + random.randint(-60, 60)
logger.success(f"{client_ip} 夜间休眠至早上8点,总休眠 {format_seconds(sleep_time)}")
time.sleep(sleep_time)
# 重置
spider_task_count = 0
rest_after = get_next_runtime(index)
start_time = int(time.time())
DeviceManager.start_app(client_ip, logger_instance)
# 正常操作
redis_conn3.hset(f"xhs_app:{client_ip}", task, '0')
redis_conn3.hset(f"xhs_app:{client_ip}:{task}", task, "1")
auto_operation(d, task, client_ip, logger_instance)
spider_task_count += 1
logger.info(f"{client_ip} {task} 已完成 任务总量 -> {spider_task_count}")
timeSleep = random.randint(3, 8)
time.sleep(timeSleep)
else:
logger.error(f"{client_ip} 当前设备无法使用 ")
continue
except KeyboardInterrupt:
logger_instance.info("进程被中断")
except Exception as e:
logger_instance.error(f"进程异常退出: {e}")
def main():
phone_num = len(search_clientip)
processes = []
for idx, ip in enumerate(search_clientip):
p = multiprocessing.Process(target=worker, args=(ip, idx))
p.start()
processes.append(p)
for p in processes:
p.join()
if __name__ == '__main__':
main()
# start_frida_via_serial("b6f8967f")
import datetime
import multiprocessing
import random
import traceback
import requests
import uiautomator2 as u2
from redis import Redis
import re
import time
import pymysql
from pymysql.err import OperationalError
from loguru import logger
import sys
import json
# ===================== 全局配置 =====================
KEYCODE_MAP = {
"0": 7, "1": 8, "2": 9, "3": 10, "4": 11,
"5": 12, "6": 13, "7": 14, "8": 15, "9": 16
}
redis_conn3 = Redis(host="172.16.0.24", password="aiyingli@@123", db=3, decode_responses=True)
common_redis0 = Redis(host="172.16.0.24", password="aiyingli@@123", db=0, decode_responses=True)
redis_conn2 = Redis(host="172.16.0.24", password="aiyingli@@123", db=2, decode_responses=True)
from tools import client_account, user_clientip, client_proxy
import subprocess
search_clientip = [
# "172.200.2.179",
# "172.200.2.109",
# "172.200.2.210",
# "172.200.2.118",
# "172.200.2.74",
# "172.200.2.132",
# "172.200.2.83",
# "172.200.2.75",
# "172.200.2.126",
# "172.200.2.81",
# "172.200.2.70",
# "172.200.4.18",
# "172.200.4.126",
# "172.200.4.11",
# # "172.200.2.196",
# "18910081473": "http://iprowq:yk2gbxo4@111.170.157.180:16816",
# "172.200.4.115",
# "18911415293": "http://iprowq:yk2gbxo4@42.51.0.234:16816",
# "172.200.4.155",
# "172.200.4.13",
# "18911482557": "http://iprowq:yk2gbxo4@117.50.201.181:16816",
# "172.200.5.70",
# "18911475707": "http://iprowq:yk2gbxo4@36.134.120.81:16816",
# "172.200.5.98",
# "18911461625": "http://iprowq:yk2gbxo4@42.51.42.254:16818",
"172.20.1.252",
"172.20.1.251",
"172.20.1.250",
"172.20.1.249",
"172.20.1.248",
"172.20.1.247",
"172.20.1.246",
]
wait_set_phone = [
"172.200.4.155",
"172.200.5.98",
"172.200.5.99",
"172.200.5.70"
]
def setup_logger(ip):
"""为每台手机创建独立的日志文件"""
log_file = f"xhs_log_{ip.replace('.', '_')}.log"
# 移除默认 logger,添加文件输出
logger.remove() # 移除默认 stdout
# logger.add(log_file, rotation="10 MB", retention="7 days", encoding="utf-8")
logger.add(sys.stderr, level="INFO") # 保留终端关键输出
return logger
class SimpleMySQL:
"""极简查询封装:只支持 SELECT * … WHERE ..."""
def __init__(self, charset="utf8mb4"):
self.cfg = dict(host="tenant-2101894307-cn-beijing-public.bytehouse.volces.com", port=3306, user="bytehouse",
password="m1wUyPHX0H:JQDqesXaoc", db="douchacha_data", charset=charset,
cursorclass=pymysql.cursors.DictCursor,
autocommit=True
)
self._conn = None
self._connect()
# ---------- public ----------
def query(self, phone_num, start_time, deadline):
sql = f"SELECT * FROM recv_sms WHERE phone_num = {phone_num} AND recv_time >= {start_time} AND recv_time <= {deadline}"
try:
return self._execute(sql)
except OperationalError as e: # 连接异常自动重连一次
print(e)
if e.args and e.args[0] in (2006, 2013):
self._reconnect()
return self._execute(sql)
raise
# ---------- private ----------
def _connect(self):
if self._conn:
self._conn.close()
self._conn = pymysql.connect(**self.cfg)
def _reconnect(self):
try:
self._connect()
except Exception as e:
raise RuntimeError(f"Reconnect failed: {e}") from e
def _execute(self, sql):
with self._conn.cursor() as cur:
cur.execute(sql)
return cur.fetchall()
def close(self):
self._conn.close()
def _ensure_conn(self):
try:
self._conn.ping(reconnect=True) # 如果断了会自动重连
except Exception as e:
logger.error(f"MySQL ping failed, reconnecting: {e}")
self._conn = self._connect() # 你自己封装的重连逻辑
def replace_into(self, table, item_list):
self._ensure_conn()
if not item_list:
return 0
try:
keys = list(item_list[0].keys())
cols = ", ".join(f"`{k}`" for k in keys)
placeholders = ", ".join(["%s"] * len(keys))
sql = f"REPLACE INTO `{table}` ({cols}) VALUES ({placeholders})"
# 处理特殊字符
def sanitize_value(value):
if value is None:
return None
if isinstance(value, str):
# 移除或转义可能引起问题的字符
return value.replace('`', '').replace('\\', '\\\\')
return value
values = [tuple(sanitize_value(item[k]) for k in keys) for item in item_list]
try:
# 🔑 关键:写之前先 ping 一下,断了就重连
self._conn.ping(reconnect=True)
with self._conn.cursor() as cur:
cur.executemany(sql, values)
# self._conn.commit()
logger.success(f"********** {table} 共写入{len(item_list)}条数据 **********")
return len(values)
except Exception as e:
logger.error(f"MySQL 执行错误: {e}")
raise
except Exception as e:
print(f"Error: {e}")
self._connect()
db = SimpleMySQL()
class DeviceRestRequired(Exception):
"""页面触发安全限制时,通知设备主循环立即进入休息。"""
def check_access_restriction(d, client_ip):
"""检测小红书的访问频繁安全限制提示。"""
access_frequent = d(textContains="访问频繁").exists
security_limited = d(textContains="安全限制").exists
retry_later = d(textContains="请稍后再试").exists
if access_frequent or (security_limited and retry_later):
message = "检测到安全限制:访问频繁,请稍后再试"
logger.error(f"{client_ip} {message},设备立即进入休息")
raise DeviceRestRequired(message)
def alert(msg):
url = "https://open.feishu.cn/open-apis/bot/v2/hook/1ac7eee2-1c29-477f-95f1-8f3f7df4a0b7"
payload = {
"msg_type": "text",
"content": {
"text": msg
}
}
try:
resp = requests.post(
url,
json=payload,
headers={"Content-Type": "application/json"},
timeout=10
)
resp.raise_for_status()
logger.info("Feishu alert sent, status=%s", resp.status_code)
except requests.RequestException as e:
logger.error("Feishu alert failed: %s", e)
class Login():
def __init__(self, client_ip):
self.client_ip = client_ip
def login(self, d, client_ip):
while 1:
page_activity = check_activity(d)
logger.success(page_activity)
if page_activity == "com.xingin.login.activity.WelcomeActivity":
# 微信登陆界面
dump_page(d, "WelcomeActivity")
if d(text="一键登录"):
logger.success("开始使用一键登录")
d.xpath('//android.widget.LinearLayout/android.widget.Button[@index="0"]').click()
time.sleep(2)
d(text="一键登录").click()
time.sleep(3)
if d(text='同意并继续'):
d(text="同意并继续").click()
time.sleep(2)
elif d(text="手机号登录").exists:
logger.success("找到使用手机号登录,开始点击操作")
d(text="手机号登录").click()
time.sleep(3)
else:
logger.error("未找到手机号登录选项,需要单独处理")
elif page_activity == "com.xingin.login.halfwelcome.HalfWelcomeActivity":
# 当前页面仅有手机号登陆
dump_page(d, "HalfWelcomeActivity")
if d(text="手机号登录").exists:
logger.success("找到手机号登录,开始点击操作")
d(text="手机号登录").click()
time.sleep(3)
else:
logger.error("未找到手机号登录选项,需要单独处理")
elif page_activity == "com.xingin.login.activity.LoginActivity":
# 手机号登陆界面
# dump_page(d,"LoginActivity")
# logger.success("写入完成")
# exit()
# time.sleep(3)
if d(description="全部删除").exists:
try:
phone_number = d(textMatches="\\d{3} \\d{4} \\d{4}").get_text()
logger.success(f"当前手机号为{phone_number}")
except:
phone_number = ""
if phone_number != "":
logger.error("直接发送短信")
logger.success("找到 全部删除 开始点击")
d(description="全部删除").click()
time.sleep(2)
el = d.xpath('//android.widget.EditText[@hint="请输入手机号码"]')
if el:
el.click()
phone = client_account[client_ip]
for char in phone:
d.send_keys(char)
time.sleep(0.1)
else:
logger.error("没有找到 el")
d(description="未选中,同意").click()
time.sleep(1)
# 4. 点击 "验证并登录"
d(text="验证并登录").click()
time.sleep(1)
account = client_account[client_ip]
code = ""
for attempt in range(1, 4):
if attempt != 1:
d(text="重新发送").click()
time.sleep(2)
logger.info(f"=== 第 {attempt} 次尝试登陆 {account} ===")
start_time = int(time.time())
deadline = start_time + 60
while time.time() < deadline:
rows = db.query(account, start_time, deadline)
if rows:
msg = rows[0]["msg"]
code = re.search(r"\b(\d{4,6})\b", msg).group(1)
break
time.sleep(3)
if not code:
logger.warning(f"{account} 第 {attempt} 次未获取到验证码,准备重试")
continue
# if attempt == MAX_RETRY:
break
if code == "":
return
logger.success(f"{account} 获取验证码成功:{code}")
d(text="输入验证码").click()
time.sleep(1)
for char in code:
d.send_keys(char)
time.sleep(0.1)
d(text="登录").click()
time.sleep(3)
elif page_activity == "com.xingin.login.device.offline.DeviceOfflineRemindActivity":
if d(text="账号下线提示"):
logger.error("当前弹窗登录掉线,点击重新登录")
d(text="重新登录").click()
time.sleep(3)
continue
elif page_activity == "com.xingin.reactnative.ui.WalifyReactActivity":
raise DeviceRestRequired("进入安全限制 Activity:com.xingin.reactnative.ui.WalifyReactActivity")
elif page_activity == "com.xingin.reactnative.ui.WalifyReactTranslucentActivity":
logger.error("当前设备验证异常")
alert(f"小红书检测设备 {client_ip} 登陆异常,请及时查看")
set_device_status(client_ip, "0")
return
elif page_activity == "com.xingin.alioth.search.GlobalSearchActivity":
return
def check_page_status(d, client_ip):
status_count = 0
while 1:
check_access_restriction(d, client_ip)
if d(text="网络好像断了,请检查手机是否联网").exists:
status_count += 1
if status_count == 5:
logger.error("连续点击*重新加载*异常 退出当前词查询 发送报警")
return False
logger.error(f'{client_ip} 网络异常 重新等待五秒后重新点击搜索')
time.sleep(3)
if d(text="重新加载").exists:
logger.error(f"{client_ip} 当前有重新加载按钮 点击重新加载")
d(text="重新加载").click()
time.sleep(2)
continue
elif d(text="搜索").exists:
logger.error("当前网络连接异常 未找到重新加载按钮,重新点击搜索")
d(text="搜索").click()
time.sleep(2)
continue
return True
def human_like_scroll(d, keyword, client_ip, max_up=2, min_delay=2.0, max_delay=4.0):
screen_width, screen_height = d.window_size()
up_count = 0
down_count = 0
continuous_down = 0 # 连续下滑计数
random_down_threshold = random.randint(3, 5) # 触发上滑的门槛(3~5 次下滑后才允许上滑)
last_spider_count = None
last_change_time = time.time()
start_time = time.time()
max_nochange_time = 1000
last_progress_time = time.time() # 只在 spider_count 变动时更新,用于 5 分钟强恢复
while True:
try:
# TODO: 退出条件 -> redis hget(f"xhs_app:{client_ip}:{keyword}", keyword) == 5 时 break
if not check_page_status(d, client_ip):
return False
if d(text="无更多内容").exists:
logger.success("采集完成 无更多内容")
return True
elif d(text="没有找到相关内容,换个词试试吧").exists:
logger.success("没有找到相关内容,换个词试试吧")
return True
try:
spider_count = redis_conn3.hget(f"xhs_app:{client_ip}", keyword)
# logger.success(f"xhs_app:{client_ip} keyword -> {keyword} spider_count -> {spider_count}", )
if spider_count is not None:
spider_count = int(spider_count)
except Exception as e:
print(f"[Redis异常] {e}")
spider_count = None
if spider_count == 5:
# logger.success(f"{keyword} 当前已拦截5次 退出滑动")
return True
if spider_count is not None:
if spider_count != last_spider_count:
# 正常进度,更新记录
last_spider_count = spider_count
last_change_time = time.time()
else:
# 计数没变化,超过15s → 认为卡住
if time.time() - last_change_time > 200:
# print("[卡顿检测] 页面长时间无变化,触发多次上滑+强力下滑容错")
# 连续上滑 2~3 次
for _ in range(random.randint(2, 3)):
d.swipe(
screen_width // 2,
int(screen_height * 0.6),
screen_width // 2,
int(screen_height * 0.8),
0.3
)
time.sleep(0.8)
# 强力下滑(90% 屏幕高度)
d.swipe(
screen_width // 2,
int(screen_height * 0.9),
screen_width // 2,
int(screen_height * 0.1),
0.5
)
time.sleep(3)
# 重置检测计时器
last_change_time = time.time() # 默认方向下滑
if time.time() - last_progress_time > max_nochange_time:
return False
# raise TimeoutError("spider_count 长时间无变化,触发强恢复")
direction = "down"
# 控制上滑逻辑:必须连续下滑 >= 随机门槛,且上滑次数不能超过 max_up
if continuous_down >= random_down_threshold and up_count < max_up and random.random() < 0.2:
direction = "up"
up_count += 1
continuous_down = 0 # 重置连续下滑计数
random_down_threshold = random.randint(3, 5) # 重新生成门槛
else:
direction = "down"
down_count += 1
continuous_down += 1
# ---- 改进的滑动区域计算(基于屏幕中间) ----
start_x = int(screen_width * 0.5 + random.randint(-50, 50)) # 中间 ±50px
start_y = int(screen_height * (0.5 + random.uniform(-0.2, 0.2))) # 中间 ±20% 高度
if direction == "down":
move_distance = int(screen_height * random.uniform(0.5, 0.7)) # 下滑距离 50%~70%
end_y = start_y - move_distance
else:
move_distance = int(screen_height * random.uniform(0.3, 0.5)) # 上滑保持中等力度
end_y = start_y + move_distance
# 边界保护,避免滑到最顶/最底
end_y = max(100, min(screen_height - 100, end_y))
duration = float(random.uniform(0.15, 0.3)) # 更快的滑动
# 执行滑动
try:
d.swipe(start_x, start_y, start_x, end_y, duration)
except Exception as e:
print(f"[滑动异常] {e}")
# 兜底强制下滑一次,避免卡死
d.swipe(screen_width // 2, int(screen_height * 0.8), screen_width // 2, int(screen_height * 0.2), 0.3)
continue
# 模拟浏览(拟人化操作)
action_chance = random.random()
if action_chance < 0.2:
# 偶尔长时间停留(认真看内容)
delay = random.uniform(5, 8)
# logger.info(f"[拟人操作] 长时间停留 {delay:.1f}s 模拟认真看内容")
time.sleep(delay)
elif action_chance < 0.3:
# 偶尔小幅度微调滑动
offset = random.randint(50, 120)
d.swipe(start_x, start_y, start_x, start_y - offset, random.uniform(0.1, 0.2))
time.sleep(random.uniform(1, 2))
elif action_chance < 0.4:
# 偶尔什么都不做,模拟发呆
delay = random.uniform(1, 3)
# logger.info(f"[拟人操作] 发呆中 {delay:.1f}s")
time.sleep(delay)
else:
# 正常停顿浏览(快速翻页)
delay = random.uniform(1, 2.0)
time.sleep(delay)
except DeviceRestRequired:
raise
except Exception as e:
logger.error(e)
continue
def phone_operation(d, command):
d.press(command)
def do_search_scroll(d, task, client_ip):
try:
if d(description="全部删除").exists:
d(description="全部删除").click()
logger.success("清空上次搜索内容")
if d(text="搜索, ").exists:
d(text="搜索, ").click()
for char in task:
d.send_keys(char)
time.sleep(random.uniform(0.1, 0.3))
if random.random() < 0.05:
d.send_keys(random.choice("abcdefghijklmnopqrstuvwxyz"))
time.sleep(0.1)
d.press("delete")
time.sleep(0.1)
d(text="搜索").click()
time.sleep(3)
if human_like_scroll(d, task, client_ip):
logger.info(client_ip + "操作成功")
return True
logger.error("操作失敗")
return False
else:
dump_page(d, "")
logger.success("没有找到当前按钮")
except DeviceRestRequired:
raise
except Exception as e:
traceback.print_exc()
logger.error(e)
class StateManager:
# 当前手机状态管理 检测账号是否异常,当前函数结束时候 需要将手机保持在 搜索页面中GlobalSearchActivity
def __init__(self, client_ip):
self.client_ip = client_ip
def check_status(self, d, client_ip):
def handler_security_ui(info):
if info.get("package") == "com.lbe.security.miui":
d(resourceId="com.lbe.security.miui:id/permission_deny_button").click()
time.sleep(2)
info = d.app_current()
if info.get("package") == "com.xingin.xhs":
while 1:
info = d.app_current()
# logger.warning(info)
activity = info.get("activity")
logger.success(f"{client_ip},{activity}")
DeviceManager.unlock(client_ip, logger)
if activity == "com.xingin.alioth.search.GlobalSearchActivity":
if d(text="服务器迷路了,晚点再试试吧").exists:
logger.error(f"{client_ip} 服务器迷路了,晚点再试试吧")
common_redis0.hset("xhs_device_status", client_ip, "0")
time.sleep(240)
continue
common_redis0.hset("xhs_device_status", client_ip, "1")
return True
elif activity in [".index.v2.IndexActivityV2", "com.xingin.xhs.index.v2.IndexActivityV2"]:
logger.success("当前手机页面处于首页,检测是否需要登陆,不需要登陆则跳转到搜索页面")
if d(text="登录发现更多精彩").exists and d(text="去登录").exists:
logger.error("当前账号掉线 重新登陆")
d(text="去登录").click()
Login(self.client_ip).login(d, client_ip)
elif d(text="账号下线提示"):
logger.error("当前弹窗登录掉线,点击重新登录")
d(text="重新登录").click()
time.sleep(3)
continue
else:
logger.success("当前无需登录,跳转到搜索页面")
if d(description="搜索").exists:
d(description="搜索").click()
time.sleep(3)
continue
elif activity in ["com.xingin.login.activity.WelcomeActivity",
"com.xingin.login.activity.LoginActivity",
"com.xingin.login.device.offline.DeviceOfflineRemindActivity",
"com.xingin.login.halfwelcome.HalfWelcomeActivity"]:
logger.success("当前正在登陆页面中,直接执行登陆程序")
Login(self.client_ip).login(d, client_ip)
elif activity == "com.xingin.reactnative.ui.WalifyReactActivity":
message = "进入安全限制 Activity:com.xingin.reactnative.ui.WalifyReactActivity"
logger.error(f"{client_ip} {message},设备立即进入休息")
raise DeviceRestRequired(message)
elif activity == "com.xingin.reactnative.ui.WalifyReactTranslucentActivity":
logger.error("当前设备验证异常")
if d(text="当前账户异常, 允许启用本地生物验证").exists:
alert(f"小红书检测设备 {client_ip} 登陆异常 状态:当前账户异常, 允许启用本地生物验证,请及时查看")
else:
alert(f"小红书检测设备 {client_ip} 登陆异常 状态:未知状态,请及时查看")
common_redis0.hset("xhs_device_status", client_ip, "0")
return False
elif activity == "com.xingin.matrix.notedetail.NoteDetailActivity":
logger.warning(f"当前进入卡片详情页,点击退出当前页面")
d.click(44, 164)
time.sleep(3)
else:
logger.error(f"当前Activity 未处理:{activity}")
time.sleep(40)
while 1:
info = d.app_current()
logger.error(f'当前页面不在小红书中:{info.get("package")}')
for i in range(5):
phone_operation(d, 'back')
time.sleep(1)
DeviceManager.start_app(client_ip, logger)
time.sleep(5)
if info.get("package") == "com.xingin.xhs":
break
else:
logger.error(f"打开小红书失败,重新尝试,当前页面为:{info.get('package')}")
time.sleep(10)
handler_security_ui(info)
continue
else:
while 1:
info = d.app_current()
logger.error(f'当前页面不在小红书中:{info.get("package")}')
for i in range(5):
phone_operation(d, 'back')
time.sleep(1)
DeviceManager.start_app(client_ip, logger)
time.sleep(5)
if info.get("package") == "com.xingin.xhs":
break
else:
logger.error(f"打开小红书失败,重新尝试,当前页面为:{info.get('package')}")
time.sleep(10)
handler_security_ui(info)
continue
def check_collection_status(self, d):
client_status = redis_conn3.hget(f"xhs_app:status:{self.client_ip}", 'status')
if client_status == "infinity":
logger.success(f"{self.client_ip} 当前已经搜索超过上限,关闭系统等待明日采集")
DeviceManager.close_app(d)
sleep_until_next_8am()
logger.success(f"{self.client_ip} 当前完成休眠,开始继续运行")
redis_conn3.hset(f"xhs_app:status:{self.client_ip}", 'status', "success")
return False
return True
class DeviceManager:
@staticmethod
def start_app(phone_ip, logger_instance):
db = SimpleMySQL()
redis_conn = Redis(host="172.16.0.24", password="aiyingli@@123", db=3, decode_responses=True)
redis_conn2 = Redis(host="172.16.0.24", password="aiyingli@@123", db=2, decode_responses=True)
keyword_count = {}
d = u2.connect(f"{phone_ip}")
d.app_start("com.xingin.xhs")
@staticmethod
def unlock(phone_ip, logger_instance):
d = u2.connect(f"{phone_ip}")
if not d.info['screenOn']:
d.screen_on() # 或 d.press("power")
logger_instance.info("打开屏幕")
model = d.device_info["model"]
if model == "Pixel 3":
if d(resourceId="com.android.systemui:id/lock_icon").exists:
logger_instance("当前处于锁屏界面")
d.swipe(0.6, 0.85, 0.6, 0.2, 0.1)
time.sleep(1)
d.xpath('//*[@resource-id="com.android.systemui:id/key0"]').click()
d.xpath('//*[@resource-id="com.android.systemui:id/key3"]').click()
d.xpath('//*[@resource-id="com.android.systemui:id/key0"]').click()
d.xpath('//*[@resource-id="com.android.systemui:id/key4"]').click()
d.xpath('//*[@resource-id="com.android.systemui:id/key2"]').click()
d.xpath('//*[@resource-id="com.android.systemui:id/key8"]').click()
d.xpath('//*[@resource-id="com.android.systemui:id/key_enter"]').click()
else:
if d(resourceId="com.android.systemui:id/keyguard_indication_area").exists:
d.swipe(0.6, 0.85, 0.6, 0.2, 0.1)
@staticmethod
def connect_app(ip_port):
print(ip_port)
result = subprocess.run(['adb', 'connect', ip_port],
capture_output=True, text=True, timeout=10)
logger.success(f'{result.stdout, result.stderr}')
@staticmethod
def close_app(d):
d.app_stop("com.xingin.xhs")
def check_activity(d):
"""检查当前 activity,返回状态 key"""
info = d.app_current()
if info.get("package") == "com.xingin.xhs":
activity = info.get("activity")
return activity
# com.xingin.xhs
else:
logger.error("当前不在小红书中,连续执行几次返回键")
DeviceManager.close_app(d)
time.sleep(5)
logger.error(f"当前页面异常: {info}")
return "react"
def sleep_until_next_8am():
"""休眠直到次日 8 点"""
now = datetime.datetime.now()
tomorrow = now + datetime.timedelta(days=1)
next_8am = datetime.datetime(year=tomorrow.year, month=tomorrow.month, day=tomorrow.day, hour=8, minute=0, second=0)
seconds = (next_8am - now).total_seconds()
logger.success(f"需要休眠 {seconds / 3600:.2f} 小时,直到 {next_8am}")
time.sleep(seconds)
def dump_page(d, name):
"""保存页面 XML,用于调试"""
xml = d.dump_hierarchy()
if not name:
name = "./xml"
else:
name = "./" + name
with open(f'{name}.xml', 'w', encoding='utf-8') as f:
f.write(xml)
def format_seconds(seconds: int) -> str:
h = seconds // 3600
m = (seconds % 3600) // 60
s = seconds % 60
return f"{h}h{m}m{s}s"
def get_next_runtime():
"""计算下一次运行时长:随机运行 1~1.5 小时。"""
return random.randint(3600, 5400)
def take_device_rest(d, client_ip, logger_instance, reason="白天休息"):
"""关闭 App 并让当前设备随机休息 40~60 分钟。"""
DeviceManager.close_app(d)
sleep_time = random.randint(2400, 3600)
logger_instance.success(f"{client_ip} {reason} {format_seconds(sleep_time)}")
time.sleep(sleep_time)
DeviceManager.start_app(client_ip, logger_instance)
time.sleep(5)
def auto_operation(d, keyword, client_ip, logger_instance):
retry = 0
max_retry = 3
state_mgr = StateManager(client_ip)
while True:
try:
if state_mgr.check_status(d, client_ip):
if do_search_scroll(d, keyword, client_ip):
break
logger.error(f"{client_ip} 当前查询异常,重试关键词 {keyword}")
DeviceManager.start_app(client_ip, logger_instance)
continue
else:
set_device_status(client_ip, "0")
except TimeoutError as e:
retry += 1
logger.error(f"{keyword} 强恢复触发({retry}/{max_retry}):{e} -> 关闭 App 休息后继续")
DeviceManager.close_app(d)
sleep_time = random.randint(60, 120)
logger.success(f"休息 {sleep_time} 秒后继续当前关键词")
time.sleep(sleep_time)
DeviceManager.start_app(client_ip, logger_instance)
time.sleep(5)
if retry >= max_retry:
break
def set_device_status(client_ip, status):
common_redis0.hset("xhs_device_status", client_ip, status)
def xxx(timestamp):
dt = datetime.datetime.fromtimestamp(timestamp)
# 格式化为年月日
return dt.strftime("%Y%m%d")
def worker(client_ip, index):
# 每个进程独立 logger
logger_instance = setup_logger(client_ip)
logger_instance.info(f"进程 {index} 启动,负责手机 {client_ip}")
spider_task_count = 0
while 1:
try:
# DeviceManager.unlock(client_ip, logger_instance)
# DeviceManager.start_app(ip, logger_instance)
"""每台手机独立进程"""
# 初始化信息
DeviceManager.connect_app(client_ip)
logger.success(client_ip)
d = u2.Device(client_ip)
DeviceManager.unlock(client_ip, logger_instance)
# current_app = d.app_current()
# print(f"当前前台应用: {current_app}")
# dump_page(d,"./te")
# return
DeviceManager.close_app(d)
time.sleep(5)
DeviceManager.start_app(client_ip, logger_instance)
time.sleep(10)
state_mgr = StateManager(client_ip)
# 初始状态检测 确认当前设备与帐号可用
if state_mgr.check_status(d, client_ip):
set_device_status(client_ip, "1")
# 初始化各种时间
rest_after = get_next_runtime()
start_time = int(time.time())
while 1:
task = common_redis0.spop("xhs:keyword:package:m:ks")
if not task:
# logger.info(f"{device_ip} 当前暂无任务,休息 1s")
time.sleep(1)
continue
if "," in task or not task:
continue
logger.success(f"{client_ip}: {task}")
if ":::" not in task:
continue
task, pt = task.split(":::")
status = common_redis0.sadd(f"xhs:keyword:package:m:ks:{xxx(time.time())}", task)
if status == 0:
logger.info(f"{task}今日已经完成采集")
continue
now = datetime.datetime.now()
# ---------- 夜间休眠逻辑 ----------
if 2 <= now.hour < 8:
DeviceManager.close_app(d)
tomorrow_8am = now.replace(hour=8, minute=0, second=0, microsecond=0)
if now.hour >= 8: # 万一跨天
tomorrow_8am += datetime.timedelta(days=1)
sleep_time = int((tomorrow_8am - now).total_seconds())
sleep_time += index * 300 + random.randint(-60, 60)
logger.success(f"{client_ip} 夜间休眠至早上8点,总休眠 {format_seconds(sleep_time)}")
time.sleep(sleep_time)
# 重新启动 app
spider_task_count = 0
rest_after = get_next_runtime()
start_time = int(time.time())
DeviceManager.start_app(client_ip, logger_instance)
time.sleep(5)
spider_task_count = 0
continue
# ---------- 白天运行逻辑 ----------
elapsed = int(time.time() - start_time)
if elapsed > rest_after:
take_device_rest(d, client_ip, logger_instance)
# 重置计时器
rest_after = get_next_runtime()
start_time = int(time.time())
# ---------- 采集量过大逻辑 ----------
if spider_task_count > 280:
logger.success(f"{client_ip} 当前搜索量大于280,立即结束今日采集并休眠到次日 8 点")
DeviceManager.close_app(d)
tomorrow_8am = now.replace(hour=8, minute=0, second=0, microsecond=0)
if now.hour >= 8:
tomorrow_8am += datetime.timedelta(days=1)
sleep_time = int((tomorrow_8am - now).total_seconds())
sleep_time += index * 300 + random.randint(-60, 60)
logger.success(f"{client_ip} 夜间休眠至早上8点,总休眠 {format_seconds(sleep_time)}")
time.sleep(sleep_time)
# 重置
spider_task_count = 0
rest_after = get_next_runtime()
start_time = int(time.time())
DeviceManager.start_app(client_ip, logger_instance)
# 正常操作
redis_conn3.hset(f"xhs_app:{client_ip}", task, '0')
redis_conn3.hset(f"xhs_app:{client_ip}:{task}", task, "1")
while True:
try:
auto_operation(d, task, client_ip, logger_instance)
break
except DeviceRestRequired as e:
take_device_rest(d, client_ip, logger_instance, f"触发安全限制,休息原因:{e}")
rest_after = get_next_runtime()
start_time = int(time.time())
spider_task_count += 1
logger.info(f"{client_ip} {task} 已完成 任务总量 -> {spider_task_count}")
timeSleep = random.randint(3, 8)
time.sleep(timeSleep)
else:
logger.error(f"{client_ip} 当前设备无法使用 ")
continue
except DeviceRestRequired as e:
take_device_rest(d, client_ip, logger_instance, f"触发安全限制,休息原因:{e}")
continue
except KeyboardInterrupt:
logger_instance.info("进程被中断")
break
except Exception as e:
logger_instance.error(f"进程异常退出: {e}")
def main():
phone_num = len(search_clientip)
processes = []
for idx, ip in enumerate(search_clientip):
p = multiprocessing.Process(target=worker, args=(ip, idx))
p.start()
processes.append(p)
for p in processes:
p.join()
if __name__ == '__main__':
main()
import datetime
import multiprocessing
import os
import random
import re
import subprocess
import time
import xml.etree.ElementTree as ET
import pymysql
# uiautomator2 和命令行 adb 必须使用同一个现有 ADB Server。
# 同一台旧版 Android 手机被两个 ADB Server 同时连接时,会反复变成 offline。
ADB_SERVER_HOST = os.environ.get("XHS_ADB_SERVER_HOST", "127.0.0.1")
ADB_SERVER_PORT = int(os.environ.get("XHS_ADB_SERVER_PORT", "5037"))
os.environ["ANDROID_ADB_SERVER_HOST"] = ADB_SERVER_HOST
os.environ["ANDROID_ADB_SERVER_PORT"] = str(ADB_SERVER_PORT)
import uiautomator2 as u2
from redis import Redis
from pymysql.err import OperationalError
from playwright.async_api import async_playwright, TimeoutError
from loguru import logger
from tools import client_account,search_clientip,user_clientip,client_proxy
# ===================== 全局配置 =====================
APP_PACKAGE = "com.xingin.xhs"
MAX_USER_FETCH_COUNT = 10
DEVICE_RETRY_INTERVAL = 5
ADB_COMMAND_TIMEOUT = 15
ADB_CONNECT_TIMEOUT = 20
ADB_STABLE_CHECKS = 5
ADB_STABLE_INTERVAL = 1
OFFLINE_ERROR_KEYWORDS = (
"device offline",
"device not found",
"device disconnected",
"unknown host service",
"connection reset",
"connection refused",
"closed",
"broken pipe",
"read timeout",
"adberror",
)
KEYCODE_MAP = {
"0": 7, "1": 8, "2": 9, "3": 10, "4": 11,
"5": 12, "6": 13, "7": 14, "8": 15, "9": 16
}
common_redis0 = Redis(host="172.16.0.24", password="aiyingli@@123", db=0, decode_responses=True)
redis_conn2 = Redis(host="172.16.0.24", password="aiyingli@@123", db=2, decode_responses=True)
def is_device_offline_error(exc):
text = str(exc).lower()
return any(keyword in text for keyword in OFFLINE_ERROR_KEYWORDS)
class SimpleMySQL:
"""极简查询封装:只支持 SELECT * … WHERE ..."""
def __init__(self, charset="utf8mb4"):
self.cfg = dict(host="tenant-2101894307-cn-beijing-public.bytehouse.volces.com", port=3306, user="bytehouse",
password="m1wUyPHX0H:JQDqesXaoc", db="douchacha_data", charset=charset,
cursorclass=pymysql.cursors.DictCursor,
autocommit=True)
self._conn = None
self._connect()
# ---------- public ----------
def query(self, phone_num, start_time, deadline):
sql = f"SELECT * FROM recv_sms WHERE phone_num = {phone_num} AND recv_time >= {start_time} AND recv_time <= {deadline}"
try:
return self._execute(sql)
except OperationalError as e: # 连接异常自动重连一次
print(e)
if e.args and e.args[0] in (2006, 2013):
self._reconnect()
return self._execute(sql)
raise
# ---------- private ----------
def _connect(self):
if self._conn:
self._conn.close()
self._conn = pymysql.connect(**self.cfg)
def _reconnect(self):
try:
self._connect()
except Exception as e:
raise RuntimeError(f"Reconnect failed: {e}") from e
def _execute(self, sql):
with self._conn.cursor() as cur:
cur.execute(sql)
return cur.fetchall()
def close(self):
self._conn.close()
db = SimpleMySQL()
class Login():
def __init__(self, client_ip):
self.client_ip = client_ip
def login(self, d):
while 1:
page_activity = check_activity(d)
# logger.success(page_activity)
if page_activity == "com.xingin.login.activity.WelcomeActivity":
# 微信登陆界面
dump_page(d, "WelcomeActivity")
if d(text="一键登录"):
logger.success("开始使用一键登录")
d.xpath('//android.widget.LinearLayout/android.widget.Button[@index="0"]').click()
time.sleep(2)
d(text="一键登录").click()
time.sleep(3)
if d(text='同意并继续'):
d(text="同意并继续").click()
time.sleep(2)
elif d(text="手机号登录").exists:
logger.success("找到使用手机号登录,开始点击操作")
d(text="手机号登录").click()
time.sleep(3)
else:
logger.error("未找到手机号登录选项,需要单独处理")
elif page_activity == "com.xingin.login.halfwelcome.HalfWelcomeActivity":
# 当前页面仅有手机号登陆
dump_page(d, "HalfWelcomeActivity")
if d(text="手机号登录").exists:
logger.success("找到手机号登录,开始点击操作")
d(text="手机号登录").click()
time.sleep(3)
else:
logger.error("未找到手机号登录选项,需要单独处理")
elif page_activity == "com.xingin.login.activity.LoginActivity":
# 手机号登陆界面
# dump_page(d,"LoginActivity")
# logger.success("写入完成")
# exit()
# time.sleep(3)
if d(description="全部删除").exists:
try:
phone_number = d(textMatches="\\d{3} \\d{4} \\d{4}").get_text()
logger.success(f"当前手机号为{phone_number}")
except:
phone_number = ""
if phone_number != "":
logger.error("直接发送短信")
logger.success("找到 全部删除 开始点击")
d(description="全部删除").click()
time.sleep(2)
el = d.xpath('//android.widget.EditText[@hint="请输入手机号码"]')
if el:
el.click()
phone = client_account.get(self.client_ip, "")
if not phone:
logger.error(f"{self.client_ip} 未配置登录手机号,跳过当前登录流程")
return
for char in phone:
d.send_keys(char)
time.sleep(0.1)
else:
logger.error("没有找到 el")
d(description="未选中,同意").click()
time.sleep(1)
# 4. 点击 "验证并登录"
d(text="验证并登录").click()
time.sleep(1)
account = client_account.get(self.client_ip, "")
if not account:
logger.error(f"{self.client_ip} 未配置验证码接收手机号,跳过当前登录流程")
return
code = ""
for attempt in range(1, 4):
if attempt != 1:
d(text="重新发送").click()
time.sleep(2)
logger.info(f"=== 第 {attempt} 次尝试登陆 {account} ===")
start_time = int(time.time())
deadline = start_time + 60
while time.time() < deadline:
rows = db.query(account, start_time, deadline)
if rows:
msg = rows[0]["msg"]
code = re.search(r"\b(\d{4,6})\b", msg).group(1)
break
time.sleep(3)
if not code:
logger.warning(f"{account} 第 {attempt} 次未获取到验证码,准备重试")
continue
# if attempt == MAX_RETRY:
break
if code == "":
return
logger.success(f"{account} 获取验证码成功:{code}")
d(text="输入验证码").click()
time.sleep(1)
for char in code:
d.send_keys(char)
time.sleep(0.1)
d(text="登录").click()
time.sleep(3)
elif page_activity == "com.xingin.login.device.offline.DeviceOfflineRemindActivity":
# 登陆界面
...
time.sleep(5)
def human_like_scroll(d, user_id, red_id, client_ip, max_up=2, min_delay=2.0, max_delay=4.0):
screen_width, screen_height = d.window_size()
up_count = 0
down_count = 0
continuous_down = 0 # 连续下滑计数
random_down_threshold = random.randint(3, 5) # 触发上滑的门槛(3~5 次下滑后才允许上滑)
last_spider_count = None
last_change_time = time.time()
start_time = time.time()
max_nochange_time = 300
last_progress_time = time.time() # 只在 spider_count 变动时更新,用于 5 分钟强恢复
while True:
# TODO: 退出条件 -> redis hget(f"xhs_app:{client_ip}:{keyword}", keyword) == 5 时 break
try:
spider_count = redis_conn2.hget(f"xhs_app:{client_ip}", user_id)
logger.success(f"xhs_app:{client_ip} user_id -> {user_id} spider_count -> {spider_count}", )
if spider_count is not None:
spider_count = int(spider_count)
else:
spider_count = 0
except Exception as e:
print(f"[Redis异常] {e}")
spider_count = None
if int(spider_count) >= MAX_USER_FETCH_COUNT:
logger.success(
f"{user_id} 当前已拦截{MAX_USER_FETCH_COUNT}次,退出滑动,收录设置为1"
)
redis_conn2.hdel(f"xhs_app:{client_ip}", user_id)
redis_conn2.hset("xhs_app:user_collect",red_id,"1")
return
if spider_count is not None:
if spider_count != last_spider_count:
# 正常进度,更新记录
last_spider_count = spider_count
last_change_time = time.time()
else:
# 计数没变化,超过15s → 认为卡住
if time.time() - last_change_time > 60:
# print("[卡顿检测] 页面长时间无变化,触发多次上滑+强力下滑容错")
# 连续上滑 2~3 次
for _ in range(random.randint(2, 3)):
d.swipe(
screen_width // 2,
int(screen_height * 0.6),
screen_width // 2,
int(screen_height * 0.8),
0.3
)
time.sleep(0.8)
# 强力下滑(90% 屏幕高度)
d.swipe(
screen_width // 2,
int(screen_height * 0.9),
screen_width // 2,
int(screen_height * 0.1),
0.5
)
time.sleep(3)
# 重置检测计时器
last_change_time = time.time() # 默认方向下滑
if time.time() - last_progress_time > max_nochange_time:
logger.error(f"[强恢复] 关键词 {user_id} 超过 {max_nochange_time}s 无进展,准备重启 App")
raise TimeoutError("spider_count 长时间无变化,触发强恢复")
direction = "down"
# 控制上滑逻辑:必须连续下滑 >= 随机门槛,且上滑次数不能超过 max_up
if continuous_down >= random_down_threshold and up_count < max_up and random.random() < 0.2:
direction = "up"
up_count += 1
continuous_down = 0 # 重置连续下滑计数
random_down_threshold = random.randint(3, 5) # 重新生成门槛
else:
direction = "down"
down_count += 1
continuous_down += 1
# ---- 改进的滑动区域计算(基于屏幕中间) ----
start_x = int(screen_width * 0.5 + random.randint(-50, 50)) # 中间 ±50px
start_y = int(screen_height * (0.5 + random.uniform(-0.2, 0.2))) # 中间 ±20% 高度
if direction == "down":
move_distance = int(screen_height * random.uniform(0.5, 0.7)) # 下滑距离 50%~70%
end_y = start_y - move_distance
else:
move_distance = int(screen_height * random.uniform(0.3, 0.5)) # 上滑保持中等力度
end_y = start_y + move_distance
# 边界保护,避免滑到最顶/最底
end_y = max(100, min(screen_height - 100, end_y))
duration = float(random.uniform(0.15, 0.3)) # 更快的滑动
# 执行滑动
try:
d.swipe(start_x, start_y, start_x, end_y, duration)
except Exception as e:
print(f"[滑动异常] {e}")
# 兜底强制下滑一次,避免卡死
d.swipe(screen_width // 2, int(screen_height * 0.8), screen_width // 2, int(screen_height * 0.2), 0.3)
continue
# 模拟浏览(拟人化操作)
action_chance = random.random()
if action_chance < 0.1:
# 偶尔长时间停留(认真看内容)
delay = random.uniform(5, 8)
# logger.info(f"[拟人操作] 长时间停留 {delay:.1f}s 模拟认真看内容")
time.sleep(delay)
elif action_chance < 0.2:
# 偶尔小幅度微调滑动
offset = random.randint(50, 120)
d.swipe(start_x, start_y, start_x, start_y - offset, random.uniform(0.1, 0.2))
# logger.info("[拟人操作] 微调滑动")
time.sleep(random.uniform(1, 2))
# elif action_chance < 0.25:
# # 偶尔点击屏幕中部
# # print("[拟人操作] 点击屏幕模拟点开内容")
# # time.sleep(random.uniform(5, 10)) # 模拟认真浏览
# # 返回键(模拟退出内容)
# # d.press("back")
# time.sleep(random.uniform(1, 2))
elif action_chance < 0.3:
# 偶尔什么都不做,模拟发呆
delay = random.uniform(2, 4)
# logger.info(f"[拟人操作] 发呆中 {delay:.1f}s")
time.sleep(delay)
else:
# 正常停顿浏览(快速翻页)
delay = random.uniform(0.2, 1.5)
time.sleep(delay)
def phone_operation(d, command):
d.press(command)
def _parse_bounds(bounds_text):
match = re.match(r"\[(\d+),(\d+)\]\[(\d+),(\d+)\]", bounds_text or "")
if not match:
return None
return tuple(map(int, match.groups()))
def _open_search_input(d, current_keyword=None):
if d(description="全部删除").exists:
d(description="全部删除").click()
logger.success("清空上次搜索内容")
time.sleep(1)
if current_keyword and d(text=current_keyword).exists:
d(text=current_keyword).click()
time.sleep(1)
if d(description="全部删除").exists:
d(description="全部删除").click()
time.sleep(1)
if d(text="搜索, ").exists:
d(text="搜索, ").click()
return True
edit = d.xpath("//android.widget.EditText")
if edit.exists:
edit.click()
return True
return False
def _input_and_submit_search(d, keyword, current_keyword=None):
if not _open_search_input(d, current_keyword):
dump_page(d, "")
logger.success("没有找到当前按钮")
return False
# 不要逐字符调用 send_keys。uiautomator2 每次调用都会查询/切换 IME
# 并发送 broadcast;长 user_id 会瞬间创建大量 ADB shell transport,
# 在 172.20.1.25 上会把 adbd 打成 closed/offline。
d.send_keys(keyword)
time.sleep(random.uniform(0.3, 0.8))
d(text="搜索").click()
time.sleep(3)
return True
def _switch_to_user_tab(d):
if d(text="用户", selected="true").exists:
return True
if d(text="用户").exists:
logger.success("点击跳转到用户")
d(text="用户").click()
time.sleep(3)
return True
return False
def _has_no_user_result(d):
empty_texts = ("暂无相关用户", "未找到相关用户", "没有找到相关用户", "暂无用户")
return any(d(text=text).exists for text in empty_texts)
def _click_first_user_result(d):
if _has_no_user_result(d):
return False
screen_width, screen_height = d.window_size()
min_top = int(screen_height * 0.12)
max_bottom = int(screen_height * 0.92)
min_width = int(screen_width * 0.35)
try:
root = ET.fromstring(d.dump_hierarchy())
except Exception as e:
logger.error(f"解析用户搜索结果页面失败: {e}")
return False
user_card_candidates = []
candidates = []
for node in root.iter("node"):
if node.attrib.get("package") != APP_PACKAGE:
continue
if node.attrib.get("clickable") != "true" or node.attrib.get("enabled") != "true":
continue
if node.attrib.get("visible-to-user") != "true":
continue
text = node.attrib.get("text") or node.attrib.get("content-desc") or ""
if text in {"搜索", "用户", "综合", "笔记", "商品", "地点", "直播"}:
continue
bounds = _parse_bounds(node.attrib.get("bounds"))
if not bounds:
continue
left, top, right, bottom = bounds
width = right - left
height = bottom - top
content_desc = node.attrib.get("content-desc") or ""
if "小红书号:" in content_desc and top >= min_top and bottom <= max_bottom:
user_card_candidates.append((top, left, right, bottom))
continue
if top < min_top or bottom > max_bottom:
continue
if width < min_width or height < 80:
continue
candidates.append((top, left, right, bottom))
if user_card_candidates:
top, left, right, bottom = sorted(user_card_candidates)[0]
d.click((left + right) // 2, (top + bottom) // 2)
time.sleep(3)
return True
if not candidates:
return False
top, left, right, bottom = sorted(candidates)[0]
d.click((left + right) // 2, (top + bottom) // 2)
time.sleep(3)
return True
def _search_user_id_first(d, user_id, red_id, client_ip):
logger.success(f"先使用 user_id 搜索达人: {user_id}")
if not _input_and_submit_search(d, user_id):
return False
if not _switch_to_user_tab(d):
logger.error("没有找到用户入口,准备使用小红书号兜底")
return False
if _click_first_user_result(d):
activity = d.app_current().get("activity")
if activity == "com.xingin.matrix.v2.profile.newpage.NewOtherUserActivity":
logger.success(f"user_id 搜索命中用户列表第一条,进入达人主页: {user_id}")
human_like_scroll(d, user_id, red_id, client_ip)
return True
logger.error(f"user_id 搜索点击第一条后未进入达人主页,当前页面: {activity}")
logger.error(f"user_id 搜索未找到用户结果: {user_id}")
return False
def do_search_scroll(d, user_id, red_id, client_ip):
if _search_user_id_first(d, user_id, red_id, client_ip):
return
if _input_and_submit_search(d, red_id, current_keyword=user_id):
# 搜索后点击查询是否搜索到用户 搜索到点击进入用户主页
# dump_page(d,"user_search.xml")
if d(text=f"小红书号:{red_id}").exists:
logger.success(f"找到用户 {red_id}")
d(text=f"小红书号:{red_id}").click()
time.sleep(3)
human_like_scroll(d, user_id, red_id, client_ip)
else:
logger.error("没有找到用户 尝试点击用户界面 进行查找")
if d(text="用户", selected="true").exists:
# logger.success("正在用户页面")
return
else:
logger.success("不在用户页面 点击跳转到用户")
d(text="用户").click()
time.sleep(3)
if d(text=f"小红书号:{red_id}").exists:
logger.success(f"找到用户 {red_id}")
d(text=f"小红书号:{red_id}").click()
time.sleep(3)
human_like_scroll(d, user_id, red_id, client_ip)
logger.success("未找到相关用户")
else:
dump_page(d, "")
logger.success("没有找到当前按钮")
class StateManager:
# 当前手机状态管理 检测账号是否异常,当前函数结束时候 需要将手机保持在 搜索页面中GlobalSearchActivity
def __init__(self, client_ip):
self.client_ip = client_ip
def check_status(self, d):
info = d.app_current()
if info.get("package") == "com.xingin.xhs":
while 1:
info = d.app_current()
activity = info.get("activity")
logger.success(activity)
if activity == "com.xingin.alioth.search.GlobalSearchActivity":
# if d(text="用户",selected="true").exists:
# # logger.success("正在用户页面")
# return
# else:
# logger.success("不在用户页面")
# d(text="用户").click()
# time.sleep(2)
# continue
return
elif activity == "com.xingin.matrix.v2.profile.newpage.NewOtherUserActivity":
logger.success("正在用户详情页面 回退")
phone_operation(d, "back")
time.sleep(3)
elif activity in [".index.v2.IndexActivityV2", "com.xingin.xhs.index.v2.IndexActivityV2"]:
logger.success("当前手机页面处于首页,检测是否需要登陆,不需要登陆则跳转到搜索页面")
if d(text="登录发现更多精彩").exists and d(text="去登录").exists:
logger.error("当前账号掉线 重新登陆")
d(text="去登录").click()
Login(self.client_ip).login(d)
elif d(text="账号下线提示").exists:
logger.error("当前弹窗登录掉线,点击重新登录")
d(text="重新登录").click()
time.sleep(3)
else:
if d(description="搜索").exists:
d(description="搜索").click()
time.sleep(3)
continue
elif activity in ["com.xingin.login.activity.WelcomeActivity",
"com.xingin.login.activity.LoginActivity",
"com.xingin.login.device.offline.DeviceOfflineRemindActivity",
"com.xingin.login.halfwelcome.HalfWelcomeActivity"]:
logger.success("当前正在登陆页面中,直接执行登陆程序")
Login(self.client_ip).login(d)
elif activity == "com.xingin.update.UpdateDialogActivity":
logger.success("当前更新弹窗 尝试点击返回")
phone_operation(d, "back")
time.sleep(1)
else:
while 1:
info = d.app_current()
logger.error(f'当前页面不在小红书中:{info.get("package")}')
for i in range(5):
phone_operation(d, 'back')
time.sleep(1)
DeviceManager.start_app(d)
time.sleep(5)
info = d.app_current()
if info.get("package") == "com.xingin.xhs":
break
else:
logger.error(f"打开小红书失败,重新尝试,当前页面为:{info.get('package')}")
time.sleep(10)
continue
class DeviceManager:
"""设备管理"""
_adb_server_ready = False
@staticmethod
def _serial(device_ip):
return device_ip if ":" in device_ip else f"{device_ip}:5555"
@classmethod
def _ensure_adb_server(cls):
if cls._adb_server_ready:
return
# start-server 在 Server 已运行时不会重启它,也不会改变任何手机连接。
env = os.environ.copy()
env["ANDROID_ADB_SERVER_PORT"] = str(ADB_SERVER_PORT)
try:
subprocess.run(
["adb", "-P", str(ADB_SERVER_PORT), "start-server"],
check=True,
text=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
timeout=ADB_CONNECT_TIMEOUT,
env=env,
)
except (subprocess.SubprocessError, OSError) as e:
raise RuntimeError(f"无法连接 ADB Server {ADB_SERVER_HOST}:{ADB_SERVER_PORT}") from e
cls._adb_server_ready = True
@staticmethod
def _run_adb(args, check=False, capture_output=True, timeout=ADB_COMMAND_TIMEOUT):
DeviceManager._ensure_adb_server()
stdout = subprocess.PIPE if capture_output else subprocess.DEVNULL
stderr = subprocess.PIPE if capture_output else subprocess.DEVNULL
try:
return subprocess.run(
["adb", "-H", ADB_SERVER_HOST, "-P", str(ADB_SERVER_PORT), *args],
check=check,
text=True,
stdout=stdout,
stderr=stderr,
timeout=timeout,
)
except subprocess.TimeoutExpired as e:
raise RuntimeError(
f"ADB 命令超时({timeout}s): {' '.join(map(str, args))}"
) from e
@staticmethod
def get_device_state(device_ip):
serial = DeviceManager._serial(device_ip)
try:
result = DeviceManager._run_adb(
["-s", serial, "get-state"],
capture_output=True,
timeout=5,
)
except Exception as e:
logger.warning(f"{serial} 获取 ADB 状态失败: {e}")
return None
state = (result.stdout or "").strip().lower()
if result.returncode == 0 and state:
return state
error = " ".join(filter(None, [
(result.stdout or "").strip(),
(result.stderr or "").strip(),
])).lower()
if "offline" in error:
return "offline"
if "unauthorized" in error:
return "unauthorized"
return None
@staticmethod
def connect_device(device_ip, force=False):
serial = DeviceManager._serial(device_ip)
state = DeviceManager.get_device_state(device_ip)
if state == "device" and not force:
return True
# 只处理当前 serial,不使用全局 disconnect/kill-server,不会触碰其他手机。
if state == "offline":
DeviceManager._run_adb(["disconnect", serial], capture_output=True)
time.sleep(0.5)
result = DeviceManager._run_adb(
["connect", serial],
capture_output=True,
timeout=ADB_CONNECT_TIMEOUT,
)
output = " ".join(filter(None, [(result.stdout or "").strip(), (result.stderr or "").strip()]))
if output:
logger.info(f"{serial} ADB({ADB_SERVER_PORT}) connect -> {output}")
return DeviceManager.get_device_state(device_ip) == "device"
@staticmethod
def wait_until_online(device_ip, retry_interval=DEVICE_RETRY_INTERVAL):
attempt = 0
stable_count = 0
while True:
state = DeviceManager.get_device_state(device_ip)
if state == "device":
stable_count += 1
if stable_count >= ADB_STABLE_CHECKS:
logger.success(
f"{DeviceManager._serial(device_ip)} ADB 已连续稳定 "
f"{ADB_STABLE_CHECKS} 秒(端口 {ADB_SERVER_PORT})"
)
return
time.sleep(ADB_STABLE_INTERVAL)
continue
stable_count = 0
attempt += 1
logger.error(
f"{device_ip} 当前 ADB 状态异常: {state or 'disconnected'},"
f"第 {attempt} 次重连"
)
try:
if DeviceManager.connect_device(device_ip, force=state == "offline"):
continue
except Exception as e:
logger.error(f"{device_ip} adb connect 异常: {e}")
time.sleep(min(retry_interval * max(1, attempt), 30))
@staticmethod
def restart_service(d, device_ip):
DeviceManager.wait_until_online(device_ip)
last_error = None
for method_name in ("healthcheck", "reset_uiautomator"):
method = getattr(d, method_name, None)
if not callable(method):
continue
try:
method()
logger.success(f"{device_ip} 执行 {method_name} 完成")
time.sleep(2)
return
except Exception as e:
last_error = e
logger.warning(f"{device_ip} 执行 {method_name} 失败: {e}")
service_factory = getattr(d, "service", None)
if callable(service_factory):
try:
service = service_factory("uiautomator")
stop = getattr(service, "stop", None)
start = getattr(service, "start", None)
if callable(stop):
stop()
time.sleep(1)
if callable(start):
start()
logger.success(f"{device_ip} uiautomator 服务已重启")
time.sleep(2)
return
except Exception as e:
last_error = e
logger.warning(f"{device_ip} 重启 uiautomator 服务失败: {e}")
if last_error:
logger.warning(f"{device_ip} 无法确认服务已重启,后续继续尝试拉起 App: {last_error}")
@staticmethod
def build_session(device_ip, recover_uiautomator=False):
DeviceManager.wait_until_online(device_ip)
# 网络 ADB 必须使用完整 serial。仅传 IP 时 adbutils 会把它当作
# 非 remote serial,在多设备 Server 上可能选错 transport,表现为
# send_keys/IME shell 偶发 device offline。
d = u2.Device(DeviceManager._serial(device_ip))
# 新建 Device 并不等于 uiautomator 服务损坏。每次重连后立刻 reset
# 会在弱稳定设备上制造命令突发,只在明确恢复 UI 服务时执行。
if recover_uiautomator:
DeviceManager.restart_service(d, device_ip)
try:
d.set_fastinput_ime(True)
except Exception as e:
logger.warning(f"{device_ip} 设置 FastInputIME 失败: {e}")
DeviceManager.start_app(d)
time.sleep(5)
return d
@staticmethod
def start_app(d):
d.app_start(APP_PACKAGE)
@staticmethod
def close_app(d):
d.app_stop(APP_PACKAGE)
def check_activity(d):
"""检查当前 activity,返回状态 key"""
info = d.app_current()
if info.get("package") == "com.xingin.xhs":
activity = info.get("activity")
return activity
else:
logger.error("当前不在小红书中,连续执行几次返回键")
DeviceManager.close_app(d)
time.sleep(5)
logger.error(f"当前页面异常: {info}")
return "react"
def sleep_until_next_8am():
"""休眠直到次日 8 点"""
now = datetime.datetime.now()
tomorrow = now + datetime.timedelta(days=1)
next_8am = datetime.datetime(year=tomorrow.year, month=tomorrow.month, day=tomorrow.day, hour=8, minute=0, second=0)
seconds = (next_8am - now).total_seconds()
logger.success(f"需要休眠 {seconds / 3600:.2f} 小时,直到 {next_8am}")
time.sleep(seconds)
def dump_page(d, name):
"""保存页面 XML,用于调试"""
xml = d.dump_hierarchy()
if not name:
name = "./xml"
else:
name = "./" + name
with open(f'{name}.xml', 'w', encoding='utf-8') as f:
f.write(xml)
def format_seconds(seconds: int) -> str:
h = seconds // 3600
m = (seconds % 3600) // 60
s = seconds % 60
return f"{h}h{m}m{s}s"
def get_next_runtime(index: int):
"""计算下一次运行时长(带错峰)"""
base_runtime = random.randint(5400, 7200) # 1.5~2 小时
offset = index * 600 + random.randint(-300, 300) # 每台错开 10 分钟,再加小随机
return max(3600, base_runtime + offset)
def auto_operation(d, user_id, red_id, client_ip):
retry = 0
max_retry = 3
state_mgr = StateManager(client_ip)
while True:
try:
state_mgr.check_status(d)
do_search_scroll(d, user_id, red_id, client_ip)
break
except TimeoutError as e:
retry += 1
logger.error(f"{red_id} 强恢复触发({retry}/{max_retry}):{e} -> 关闭 App 休息后继续")
DeviceManager.close_app(d)
sleep_time = random.randint(60, 120)
logger.success(f"休息 {sleep_time} 秒后继续当前关键词")
time.sleep(sleep_time)
DeviceManager.start_app(d)
time.sleep(5)
if retry >= max_retry:
break
def worker(device_ip, index=0):
"""每台手机独立进程"""
client_ip = device_ip
d = None
pending_task = None
while True:
try:
if d is None:
d = DeviceManager.build_session(device_ip)
StateManager(client_ip).check_status(d)
if pending_task is None:
pending_task = common_redis0.spop("xhs:keyword:package:us2")
if not pending_task:
logger.info(f"{device_ip} 当前暂无任务,休息 5s")
time.sleep(5)
continue
try:
user_id, red_id = pending_task.split(":::", 1)
except ValueError:
logger.error(f"{device_ip} 任务格式异常,丢弃任务: {pending_task}")
pending_task = None
continue
logger.success(f"{device_ip} 当前搜索用户:{user_id} {red_id}")
auto_operation(d, user_id, red_id, client_ip)
pending_task = None
except Exception as e:
adb_state = DeviceManager.get_device_state(device_ip)
adb_offline = (
adb_state in ("offline", "unauthorized")
# 传输层异常和状态查询存在竞态:即使随后 get-state 短暂返回
# device,也不能继续对旧的 uiautomator/ADB 会话发命令。
or is_device_offline_error(e)
)
if adb_offline:
logger.exception(
f"{device_ip} ADB 状态异常({adb_state or 'disconnected'}),"
"准备重建当前手机会话"
)
d = None
else:
logger.exception(
f"{device_ip} ADB 仍在线,保留当前任务并仅恢复 uiautomator 服务"
)
if d is not None:
try:
DeviceManager.restart_service(d, device_ip)
except Exception as recovery_error:
logger.warning(f"{device_ip} uiautomator 恢复失败,将重建会话: {recovery_error}")
d = None
time.sleep(DEVICE_RETRY_INTERVAL)
def main():
logger.info(
f"本程序使用现有 ADB Server {ADB_SERVER_HOST}:{ADB_SERVER_PORT},"
"所有恢复命令都限定到当前手机,不操作其他手机连接"
)
processes = {}
try:
while True:
for idx, ip in enumerate(user_clientip):
process = processes.get(ip)
if process and process.is_alive():
continue
if process is not None:
logger.error(f"{ip} 子进程已退出,exitcode={process.exitcode},准备重新拉起")
process.join(timeout=1)
process = multiprocessing.Process(target=worker, args=(ip, idx))
process.start()
processes[ip] = process
logger.success(f"{ip} 子进程启动成功,pid={process.pid}")
time.sleep(5)
except KeyboardInterrupt:
logger.warning("收到退出信号,准备关闭所有子进程")
for process in processes.values():
if process.is_alive():
process.terminate()
for process in processes.values():
process.join(timeout=3)
if __name__ == '__main__':
main()
import datetime
import multiprocessing
import random
import re
import subprocess
import time
import pymysql
import uiautomator2 as u2
from redis import Redis
from pymysql.err import OperationalError
from playwright.async_api import async_playwright, TimeoutError
from loguru import logger
from tools import client_account,search_clientip,user_clientip,client_proxy
# ===================== 全局配置 =====================
APP_PACKAGE = "com.xingin.xhs"
DEVICE_RETRY_INTERVAL = 5
OFFLINE_ERROR_KEYWORDS = (
"device offline",
"device not found",
"device disconnected",
"unknown host service",
"connection reset",
"connection refused",
"closed",
"broken pipe",
"read timeout",
"adberror",
"uiautomator",
)
KEYCODE_MAP = {
"0": 7, "1": 8, "2": 9, "3": 10, "4": 11,
"5": 12, "6": 13, "7": 14, "8": 15, "9": 16
}
common_redis0 = Redis(host="172.16.0.24", password="aiyingli@@123", db=0, decode_responses=True)
redis_conn2 = Redis(host="172.16.0.24", password="aiyingli@@123", db=2, decode_responses=True)
def is_device_offline_error(exc):
text = str(exc).lower()
return any(keyword in text for keyword in OFFLINE_ERROR_KEYWORDS)
class SimpleMySQL:
"""极简查询封装:只支持 SELECT * … WHERE ..."""
def __init__(self, charset="utf8mb4"):
self.cfg = dict(host="tenant-2101894307-cn-beijing-public.bytehouse.volces.com", port=3306, user="bytehouse",
password="m1wUyPHX0H:JQDqesXaoc", db="douchacha_data", charset=charset,
cursorclass=pymysql.cursors.DictCursor,
autocommit=True)
self._conn = None
self._connect()
# ---------- public ----------
def query(self, phone_num, start_time, deadline):
sql = f"SELECT * FROM recv_sms WHERE phone_num = {phone_num} AND recv_time >= {start_time} AND recv_time <= {deadline}"
try:
return self._execute(sql)
except OperationalError as e: # 连接异常自动重连一次
print(e)
if e.args and e.args[0] in (2006, 2013):
self._reconnect()
return self._execute(sql)
raise
# ---------- private ----------
def _connect(self):
if self._conn:
self._conn.close()
self._conn = pymysql.connect(**self.cfg)
def _reconnect(self):
try:
self._connect()
except Exception as e:
raise RuntimeError(f"Reconnect failed: {e}") from e
def _execute(self, sql):
with self._conn.cursor() as cur:
cur.execute(sql)
return cur.fetchall()
def close(self):
self._conn.close()
db = SimpleMySQL()
class Login():
def __init__(self, client_ip):
self.client_ip = client_ip
def login(self, d):
while 1:
page_activity = check_activity(d)
# logger.success(page_activity)
if page_activity == "com.xingin.login.activity.WelcomeActivity":
# 微信登陆界面
dump_page(d, "WelcomeActivity")
if d(text="一键登录"):
logger.success("开始使用一键登录")
d.xpath('//android.widget.LinearLayout/android.widget.Button[@index="0"]').click()
time.sleep(2)
d(text="一键登录").click()
time.sleep(3)
if d(text='同意并继续'):
d(text="同意并继续").click()
time.sleep(2)
elif d(text="手机号登录").exists:
logger.success("找到使用手机号登录,开始点击操作")
d(text="手机号登录").click()
time.sleep(3)
else:
logger.error("未找到手机号登录选项,需要单独处理")
elif page_activity == "com.xingin.login.halfwelcome.HalfWelcomeActivity":
# 当前页面仅有手机号登陆
dump_page(d, "HalfWelcomeActivity")
if d(text="手机号登录").exists:
logger.success("找到手机号登录,开始点击操作")
d(text="手机号登录").click()
time.sleep(3)
else:
logger.error("未找到手机号登录选项,需要单独处理")
elif page_activity == "com.xingin.login.activity.LoginActivity":
# 手机号登陆界面
# dump_page(d,"LoginActivity")
# logger.success("写入完成")
# exit()
# time.sleep(3)
if d(description="全部删除").exists:
try:
phone_number = d(textMatches="\\d{3} \\d{4} \\d{4}").get_text()
logger.success(f"当前手机号为{phone_number}")
except:
phone_number = ""
if phone_number != "":
logger.error("直接发送短信")
logger.success("找到 全部删除 开始点击")
d(description="全部删除").click()
time.sleep(2)
el = d.xpath('//android.widget.EditText[@hint="请输入手机号码"]')
if el:
el.click()
phone = client_account.get(self.client_ip, "")
if not phone:
logger.error(f"{self.client_ip} 未配置登录手机号,跳过当前登录流程")
return
for char in phone:
d.send_keys(char)
time.sleep(0.1)
else:
logger.error("没有找到 el")
d(description="未选中,同意").click()
time.sleep(1)
# 4. 点击 "验证并登录"
d(text="验证并登录").click()
time.sleep(1)
account = client_account.get(self.client_ip, "")
if not account:
logger.error(f"{self.client_ip} 未配置验证码接收手机号,跳过当前登录流程")
return
code = ""
for attempt in range(1, 4):
if attempt != 1:
d(text="重新发送").click()
time.sleep(2)
logger.info(f"=== 第 {attempt} 次尝试登陆 {account} ===")
start_time = int(time.time())
deadline = start_time + 60
while time.time() < deadline:
rows = db.query(account, start_time, deadline)
if rows:
msg = rows[0]["msg"]
code = re.search(r"\b(\d{4,6})\b", msg).group(1)
break
time.sleep(3)
if not code:
logger.warning(f"{account} 第 {attempt} 次未获取到验证码,准备重试")
continue
# if attempt == MAX_RETRY:
break
if code == "":
return
logger.success(f"{account} 获取验证码成功:{code}")
d(text="输入验证码").click()
time.sleep(1)
for char in code:
d.send_keys(char)
time.sleep(0.1)
d(text="登录").click()
time.sleep(3)
elif page_activity == "com.xingin.login.device.offline.DeviceOfflineRemindActivity":
# 登陆界面
...
time.sleep(5)
def human_like_scroll(d, user_id, red_id, client_ip, max_up=2, min_delay=2.0, max_delay=4.0):
screen_width, screen_height = d.window_size()
up_count = 0
down_count = 0
continuous_down = 0 # 连续下滑计数
random_down_threshold = random.randint(3, 5) # 触发上滑的门槛(3~5 次下滑后才允许上滑)
last_spider_count = None
last_change_time = time.time()
start_time = time.time()
max_nochange_time = 300
last_progress_time = time.time() # 只在 spider_count 变动时更新,用于 5 分钟强恢复
while True:
# TODO: 退出条件 -> redis hget(f"xhs_app:{client_ip}:{keyword}", keyword) == 5 时 break
try:
spider_count = redis_conn2.hget(f"xhs_app:{client_ip}", user_id)
logger.success(f"xhs_app:{client_ip} user_id -> {user_id} spider_count -> {spider_count}", )
if spider_count is not None:
spider_count = int(spider_count)
else:
spider_count = 0
except Exception as e:
print(f"[Redis异常] {e}")
spider_count = None
if int(spider_count) >= 15:
logger.success(f"{user_id} 当前已拦截15次 退出滑动 收录设置为1")
redis_conn2.hdel(f"xhs_app:{client_ip}", user_id)
redis_conn2.hset("xhs_app:user_collect",red_id,"1")
return
if spider_count is not None:
if spider_count != last_spider_count:
# 正常进度,更新记录
last_spider_count = spider_count
last_change_time = time.time()
else:
# 计数没变化,超过15s → 认为卡住
if time.time() - last_change_time > 60:
# print("[卡顿检测] 页面长时间无变化,触发多次上滑+强力下滑容错")
# 连续上滑 2~3 次
for _ in range(random.randint(2, 3)):
d.swipe(
screen_width // 2,
int(screen_height * 0.6),
screen_width // 2,
int(screen_height * 0.8),
0.3
)
time.sleep(0.8)
# 强力下滑(90% 屏幕高度)
d.swipe(
screen_width // 2,
int(screen_height * 0.9),
screen_width // 2,
int(screen_height * 0.1),
0.5
)
time.sleep(3)
# 重置检测计时器
last_change_time = time.time() # 默认方向下滑
if time.time() - last_progress_time > max_nochange_time:
logger.error(f"[强恢复] 关键词 {user_id} 超过 {max_nochange_time}s 无进展,准备重启 App")
raise TimeoutError("spider_count 长时间无变化,触发强恢复")
direction = "down"
# 控制上滑逻辑:必须连续下滑 >= 随机门槛,且上滑次数不能超过 max_up
if continuous_down >= random_down_threshold and up_count < max_up and random.random() < 0.2:
direction = "up"
up_count += 1
continuous_down = 0 # 重置连续下滑计数
random_down_threshold = random.randint(3, 5) # 重新生成门槛
else:
direction = "down"
down_count += 1
continuous_down += 1
# ---- 改进的滑动区域计算(基于屏幕中间) ----
start_x = int(screen_width * 0.5 + random.randint(-50, 50)) # 中间 ±50px
start_y = int(screen_height * (0.5 + random.uniform(-0.2, 0.2))) # 中间 ±20% 高度
if direction == "down":
move_distance = int(screen_height * random.uniform(0.5, 0.7)) # 下滑距离 50%~70%
end_y = start_y - move_distance
else:
move_distance = int(screen_height * random.uniform(0.3, 0.5)) # 上滑保持中等力度
end_y = start_y + move_distance
# 边界保护,避免滑到最顶/最底
end_y = max(100, min(screen_height - 100, end_y))
duration = float(random.uniform(0.15, 0.3)) # 更快的滑动
# 执行滑动
try:
d.swipe(start_x, start_y, start_x, end_y, duration)
except Exception as e:
print(f"[滑动异常] {e}")
# 兜底强制下滑一次,避免卡死
d.swipe(screen_width // 2, int(screen_height * 0.8), screen_width // 2, int(screen_height * 0.2), 0.3)
continue
# 模拟浏览(拟人化操作)
action_chance = random.random()
if action_chance < 0.1:
# 偶尔长时间停留(认真看内容)
delay = random.uniform(5, 8)
# logger.info(f"[拟人操作] 长时间停留 {delay:.1f}s 模拟认真看内容")
time.sleep(delay)
elif action_chance < 0.2:
# 偶尔小幅度微调滑动
offset = random.randint(50, 120)
d.swipe(start_x, start_y, start_x, start_y - offset, random.uniform(0.1, 0.2))
# logger.info("[拟人操作] 微调滑动")
time.sleep(random.uniform(1, 2))
# elif action_chance < 0.25:
# # 偶尔点击屏幕中部
# # print("[拟人操作] 点击屏幕模拟点开内容")
# # time.sleep(random.uniform(5, 10)) # 模拟认真浏览
# # 返回键(模拟退出内容)
# # d.press("back")
# time.sleep(random.uniform(1, 2))
elif action_chance < 0.3:
# 偶尔什么都不做,模拟发呆
delay = random.uniform(2, 4)
# logger.info(f"[拟人操作] 发呆中 {delay:.1f}s")
time.sleep(delay)
else:
# 正常停顿浏览(快速翻页)
delay = random.uniform(0.2, 1.5)
time.sleep(delay)
def phone_operation(d, command):
d.press(command)
def do_search_scroll(d, user_id, red_id, client_ip):
if d(description="全部删除").exists:
d(description="全部删除").click()
logger.success("清空上次搜索内容")
if d(text="搜索, ").exists:
d(text="搜索, ").click()
for char in red_id:
d.send_keys(char)
time.sleep(random.uniform(0.1, 0.3))
if random.random() < 0.05:
d.send_keys(random.choice("abcdefghijklmnopqrstuvwxyz"))
time.sleep(0.1)
d.press("delete")
time.sleep(0.1)
d(text="搜索").click()
time.sleep(3)
# 搜索后点击查询是否搜索到用户 搜索到点击进入用户主页
# dump_page(d,"user_search.xml")
if d(text=f"小红书号:{red_id}").exists:
logger.success(f"找到用户 {red_id}")
d(text=f"小红书号:{red_id}").click()
time.sleep(3)
human_like_scroll(d, user_id, red_id, client_ip)
else:
logger.error("没有找到用户 尝试点击用户界面 进行查找")
if d(text="用户", selected="true").exists:
# logger.success("正在用户页面")
return
else:
logger.success("不在用户页面 点击跳转到用户")
d(text="用户").click()
time.sleep(3)
if d(text=f"小红书号:{red_id}").exists:
logger.success(f"找到用户 {red_id}")
d(text=f"小红书号:{red_id}").click()
time.sleep(3)
human_like_scroll(d, user_id, red_id, client_ip)
logger.success("未找到相关用户")
else:
dump_page(d, "")
logger.success("没有找到当前按钮")
class StateManager:
# 当前手机状态管理 检测账号是否异常,当前函数结束时候 需要将手机保持在 搜索页面中GlobalSearchActivity
def __init__(self, client_ip):
self.client_ip = client_ip
def check_status(self, d):
info = d.app_current()
if info.get("package") == "com.xingin.xhs":
while 1:
info = d.app_current()
activity = info.get("activity")
logger.success(activity)
if activity == "com.xingin.alioth.search.GlobalSearchActivity":
# if d(text="用户",selected="true").exists:
# # logger.success("正在用户页面")
# return
# else:
# logger.success("不在用户页面")
# d(text="用户").click()
# time.sleep(2)
# continue
return
elif activity == "com.xingin.matrix.v2.profile.newpage.NewOtherUserActivity":
logger.success("正在用户详情页面 回退")
phone_operation(d, "back")
time.sleep(3)
elif activity in [".index.v2.IndexActivityV2", "com.xingin.xhs.index.v2.IndexActivityV2"]:
logger.success("当前手机页面处于首页,检测是否需要登陆,不需要登陆则跳转到搜索页面")
if d(text="登录发现更多精彩").exists and d(text="去登录").exists:
logger.error("当前账号掉线 重新登陆")
d(text="去登录").click()
Login(self.client_ip).login(d)
elif d(text="账号下线提示"):
logger.error("当前弹窗登录掉线,点击重新登录")
d(text="重新登录").click()
time.sleep(3)
else:
if d(description="搜索").exists:
d(description="搜索").click()
time.sleep(3)
continue
elif activity in ["com.xingin.login.activity.WelcomeActivity",
"com.xingin.login.activity.LoginActivity",
"com.xingin.login.device.offline.DeviceOfflineRemindActivity",
"com.xingin.login.halfwelcome.HalfWelcomeActivity"]:
logger.success("当前正在登陆页面中,直接执行登陆程序")
Login(self.client_ip).login(d)
elif activity == "com.xingin.update.UpdateDialogActivity":
logger.success("当前更新弹窗 尝试点击返回")
phone_operation(d, "back")
time.sleep(1)
else:
while 1:
logger.error(f'当前页面不在小红书中:{info.get("package")}')
for i in range(5):
phone_operation(d, 'back')
time.sleep(1)
DeviceManager.start_app(d)
time.sleep(5)
if info.get("package") == "com.xingin.xhs":
break
else:
logger.error(f"打开小红书失败,重新尝试,当前页面为:{info.get('package')}")
time.sleep(10)
continue
class DeviceManager:
"""设备管理"""
@staticmethod
def _run_adb(args, check=False, capture_output=True):
stdout = subprocess.PIPE if capture_output else subprocess.DEVNULL
stderr = subprocess.PIPE if capture_output else subprocess.DEVNULL
return subprocess.run(
["adb", *args],
check=check,
text=True,
stdout=stdout,
stderr=stderr,
)
@staticmethod
def _serial_matches(device_ip, serial):
return serial == device_ip or serial.startswith(f"{device_ip}:")
@staticmethod
def get_device_state(device_ip):
try:
result = DeviceManager._run_adb(["devices"], capture_output=True)
except Exception as e:
logger.error(f"{device_ip} 获取 adb devices 失败: {e}")
return None
for line in (result.stdout or "").splitlines():
line = line.strip()
if not line or line.startswith("List of devices"):
continue
parts = line.split()
if len(parts) >= 2 and DeviceManager._serial_matches(device_ip, parts[0]):
return parts[1]
return None
@staticmethod
def connect_device(device_ip, force=False):
state = DeviceManager.get_device_state(device_ip)
if state == "device" and not force:
return True
if state == "offline":
DeviceManager._run_adb(["disconnect", device_ip], capture_output=True)
time.sleep(1)
result = DeviceManager._run_adb(["connect", device_ip], capture_output=True)
output = " ".join(filter(None, [(result.stdout or "").strip(), (result.stderr or "").strip()]))
if output:
logger.info(f"{device_ip} adb connect -> {output}")
return DeviceManager.get_device_state(device_ip) == "device"
@staticmethod
def wait_until_online(device_ip, retry_interval=DEVICE_RETRY_INTERVAL):
while True:
state = DeviceManager.get_device_state(device_ip)
if state == "device":
logger.success(f"{device_ip} ADB 已在线")
return
logger.error(f"{device_ip} 当前 ADB 状态异常: {state or 'disconnected'},开始重连手机")
try:
DeviceManager.connect_device(device_ip, force=True)
except Exception as e:
logger.error(f"{device_ip} adb connect 异常: {e}")
time.sleep(retry_interval)
@staticmethod
def restart_service(d, device_ip):
last_error = None
for method_name in ("healthcheck", "reset_uiautomator"):
method = getattr(d, method_name, None)
if not callable(method):
continue
try:
method()
logger.success(f"{device_ip} 执行 {method_name} 完成")
time.sleep(2)
return
except Exception as e:
last_error = e
logger.warning(f"{device_ip} 执行 {method_name} 失败: {e}")
service_factory = getattr(d, "service", None)
if callable(service_factory):
try:
service = service_factory("uiautomator")
stop = getattr(service, "stop", None)
start = getattr(service, "start", None)
if callable(stop):
stop()
time.sleep(1)
if callable(start):
start()
logger.success(f"{device_ip} uiautomator 服务已重启")
time.sleep(2)
return
except Exception as e:
last_error = e
logger.warning(f"{device_ip} 重启 uiautomator 服务失败: {e}")
if last_error:
logger.warning(f"{device_ip} 无法确认服务已重启,后续继续尝试拉起 App: {last_error}")
@staticmethod
def build_session(device_ip):
DeviceManager.wait_until_online(device_ip)
d = u2.Device(device_ip)
DeviceManager.restart_service(d, device_ip)
try:
d.set_fastinput_ime(True)
except Exception as e:
logger.warning(f"{device_ip} 设置 FastInputIME 失败: {e}")
DeviceManager.start_app(d)
time.sleep(5)
return d
@staticmethod
def start_app(d):
d.app_start(APP_PACKAGE)
@staticmethod
def close_app(d):
d.app_stop(APP_PACKAGE)
def check_activity(d):
"""检查当前 activity,返回状态 key"""
info = d.app_current()
if info.get("package") == "com.xingin.xhs":
activity = info.get("activity")
return activity
else:
logger.error("当前不在小红书中,连续执行几次返回键")
DeviceManager.close_app(d)
time.sleep(5)
logger.error(f"当前页面异常: {info}")
return "react"
def sleep_until_next_8am():
"""休眠直到次日 8 点"""
now = datetime.datetime.now()
tomorrow = now + datetime.timedelta(days=1)
next_8am = datetime.datetime(year=tomorrow.year, month=tomorrow.month, day=tomorrow.day, hour=8, minute=0, second=0)
seconds = (next_8am - now).total_seconds()
logger.success(f"需要休眠 {seconds / 3600:.2f} 小时,直到 {next_8am}")
time.sleep(seconds)
def dump_page(d, name):
"""保存页面 XML,用于调试"""
xml = d.dump_hierarchy()
if not name:
name = "./xml"
else:
name = "./" + name
with open(f'{name}.xml', 'w', encoding='utf-8') as f:
f.write(xml)
def format_seconds(seconds: int) -> str:
h = seconds // 3600
m = (seconds % 3600) // 60
s = seconds % 60
return f"{h}h{m}m{s}s"
def get_next_runtime(index: int):
"""计算下一次运行时长(带错峰)"""
base_runtime = random.randint(5400, 7200) # 1.5~2 小时
offset = index * 600 + random.randint(-300, 300) # 每台错开 10 分钟,再加小随机
return max(3600, base_runtime + offset)
def auto_operation(d, user_id, red_id, client_ip):
retry = 0
max_retry = 3
state_mgr = StateManager(client_ip)
while True:
try:
state_mgr.check_status(d)
do_search_scroll(d, user_id, red_id, client_ip)
break
except TimeoutError as e:
retry += 1
logger.error(f"{red_id} 强恢复触发({retry}/{max_retry}):{e} -> 关闭 App 休息后继续")
DeviceManager.close_app(d)
sleep_time = random.randint(60, 120)
logger.success(f"休息 {sleep_time} 秒后继续当前关键词")
time.sleep(sleep_time)
DeviceManager.start_app(d)
time.sleep(5)
if retry >= max_retry:
break
def worker(device_ip, index=0):
"""每台手机独立进程"""
client_ip = device_ip
d = None
pending_task = None
while True:
try:
if d is None:
d = DeviceManager.build_session(device_ip)
StateManager(client_ip).check_status(d)
if pending_task is None:
pending_task = common_redis0.spop("xhs:keyword:package:us2")
if not pending_task:
logger.info(f"{device_ip} 当前暂无任务,休息 5s")
time.sleep(5)
continue
try:
user_id, red_id = pending_task.split(":::", 1)
except ValueError:
logger.error(f"{device_ip} 任务格式异常,丢弃任务: {pending_task}")
pending_task = None
continue
logger.success(f"{device_ip} 当前搜索用户:{user_id} {red_id}")
auto_operation(d, user_id, red_id, client_ip)
pending_task = None
except Exception as e:
if is_device_offline_error(e):
logger.exception(f"{device_ip} 手机离线,准备重连手机并重启服务")
else:
logger.exception(f"{device_ip} 运行异常,保留当前任务并尝试恢复")
d = None
time.sleep(DEVICE_RETRY_INTERVAL)
def main():
processes = {}
try:
while True:
for idx, ip in enumerate(user_clientip):
process = processes.get(ip)
if process and process.is_alive():
continue
if process is not None:
logger.error(f"{ip} 子进程已退出,exitcode={process.exitcode},准备重新拉起")
process.join(timeout=1)
process = multiprocessing.Process(target=worker, args=(ip, idx))
process.start()
processes[ip] = process
logger.success(f"{ip} 子进程启动成功,pid={process.pid}")
time.sleep(5)
except KeyboardInterrupt:
logger.warning("收到退出信号,准备关闭所有子进程")
for process in processes.values():
if process.is_alive():
process.terminate()
for process in processes.values():
process.join(timeout=3)
if __name__ == '__main__':
main()
import datetime
import multiprocessing
import random
import requests
import uiautomator2 as u2
from redis import Redis
import re
import time
import pymysql
from pymysql.err import OperationalError
from loguru import logger
from tools import client_account, search_clientip, user_clientip, client_proxy
import subprocess
# ===================== 全局配置 =====================
KEYCODE_MAP = {
"0": 7, "1": 8, "2": 9, "3": 10, "4": 11,
"5": 12, "6": 13, "7": 14, "8": 15, "9": 16
}
redis_conn3 = Redis(host="172.16.0.24", password="aiyingli@@123", db=3, decode_responses=True)
common_redis0 = Redis(host="172.16.0.24", password="aiyingli@@123", db=0, decode_responses=True)
redis_conn2 = Redis(host="172.16.0.24", password="aiyingli@@123", db=2, decode_responses=True)
class SimpleMySQL:
"""极简查询封装:只支持 SELECT * … WHERE ..."""
def __init__(self, charset="utf8mb4"):
self.cfg = dict(host="tenant-2101894307-cn-beijing-public.bytehouse.volces.com", port=3306, user="bytehouse",
password="m1wUyPHX0H:JQDqesXaoc", db="douchacha_data", charset=charset,
cursorclass=pymysql.cursors.DictCursor,
autocommit=True
)
self._conn = None
self._connect()
# ---------- public ----------
def query(self, phone_num, start_time, deadline):
sql = f"SELECT * FROM recv_sms WHERE phone_num = {phone_num} AND recv_time >= {start_time} AND recv_time <= {deadline}"
try:
return self._execute(sql)
except OperationalError as e: # 连接异常自动重连一次
print(e)
if e.args and e.args[0] in (2006, 2013):
self._reconnect()
return self._execute(sql)
raise
# ---------- private ----------
def _connect(self):
if self._conn:
self._conn.close()
self._conn = pymysql.connect(**self.cfg)
def _reconnect(self):
try:
self._connect()
except Exception as e:
raise RuntimeError(f"Reconnect failed: {e}") from e
def _execute(self, sql):
with self._conn.cursor() as cur:
cur.execute(sql)
return cur.fetchall()
def close(self):
self._conn.close()
db = SimpleMySQL()
def alert(msg):
url = "https://open.feishu.cn/open-apis/bot/v2/hook/1d0aa56a-ed39-4128-b445-ba953b32444b"
payload = {
"msg_type": "text",
"content": {
"text": msg
}
}
try:
resp = requests.post(
url,
json=payload,
headers={"Content-Type": "application/json"},
timeout=10
)
resp.raise_for_status()
logger.info("Feishu alert sent, status=%s", resp.status_code)
except requests.RequestException as e:
logger.error("Feishu alert failed: %s", e)
class Login():
def __init__(self, client_ip):
self.client_ip = client_ip
def login(self, d, client_ip):
while 1:
page_activity = check_activity(d)
logger.success(page_activity)
if page_activity == "com.xingin.login.activity.WelcomeActivity":
# 微信登陆界面
dump_page(d, "WelcomeActivity")
if d(text="一键登录"):
logger.success("开始使用一键登录")
d.xpath('//android.widget.LinearLayout/android.widget.Button[@index="0"]').click()
time.sleep(2)
d(text="一键登录").click()
time.sleep(3)
if d(text='同意并继续'):
d(text="同意并继续").click()
time.sleep(2)
elif d(text="手机号登录").exists:
logger.success("找到使用手机号登录,开始点击操作")
d(text="手机号登录").click()
time.sleep(3)
else:
logger.error("未找到手机号登录选项,需要单独处理")
elif page_activity == "com.xingin.login.halfwelcome.HalfWelcomeActivity":
# 当前页面仅有手机号登陆
dump_page(d, "HalfWelcomeActivity")
if d(text="手机号登录").exists:
logger.success("找到手机号登录,开始点击操作")
d(text="手机号登录").click()
time.sleep(3)
else:
logger.error("未找到手机号登录选项,需要单独处理")
elif page_activity == "com.xingin.login.activity.LoginActivity":
# 手机号登陆界面
# dump_page(d,"LoginActivity")
# logger.success("写入完成")
# exit()
# time.sleep(3)
if d(description="全部删除").exists:
try:
phone_number = d(textMatches="\\d{3} \\d{4} \\d{4}").get_text()
logger.success(f"当前手机号为{phone_number}")
except:
phone_number = ""
if phone_number != "":
logger.error("直接发送短信")
logger.success("找到 全部删除 开始点击")
d(description="全部删除").click()
time.sleep(2)
el = d.xpath('//android.widget.EditText[@hint="请输入手机号码"]')
if el:
el.click()
phone = client_account[client_ip]
for char in phone:
d.send_keys(char)
time.sleep(0.1)
else:
logger.error("没有找到 el")
d(description="未选中,同意").click()
time.sleep(1)
# 4. 点击 "验证并登录"
d(text="验证并登录").click()
time.sleep(1)
account = client_account[client_ip]
code = ""
for attempt in range(1, 4):
if attempt != 1:
d(text="重新发送").click()
time.sleep(2)
logger.info(f"=== 第 {attempt} 次尝试登陆 {account} ===")
start_time = int(time.time())
deadline = start_time + 60
while time.time() < deadline:
rows = db.query(account, start_time, deadline)
if rows:
msg = rows[0]["msg"]
code = re.search(r"\b(\d{4,6})\b", msg).group(1)
break
time.sleep(3)
if not code:
logger.warning(f"{account} 第 {attempt} 次未获取到验证码,准备重试")
continue
# if attempt == MAX_RETRY:
break
if code == "":
return
logger.success(f"{account} 获取验证码成功:{code}")
d(text="输入验证码").click()
time.sleep(1)
for char in code:
d.send_keys(char)
time.sleep(0.1)
d(text="登录").click()
time.sleep(3)
elif page_activity == "com.xingin.login.device.offline.DeviceOfflineRemindActivity":
if d(text="账号下线提示"):
logger.error("当前弹窗登录掉线,点击重新登录")
d(text="重新登录").click()
time.sleep(3)
continue
elif page_activity == "com.xingin.reactnative.ui.WalifyReactTranslucentActivity":
logger.error("当前设备验证异常")
alert(f"小红书检测设备 {client_ip} 登陆异常,请及时查看")
set_device_status(client_ip, "0")
return
elif page_activity == "com.xingin.alioth.search.GlobalSearchActivity":
return
def check_page_status(d, client_ip):
status_count = 0
while 1:
if d(text="网络好像断了,请检查手机是否联网").exists:
status_count += 1
if status_count == 5:
logger.error("连续点击*重新加载*异常 退出当前词查询 发送报警")
return False
logger.error(f'{client_ip} 网络异常 重新等待五秒后重新点击搜索')
time.sleep(3)
if d(text="重新加载").exists:
logger.error(f"{client_ip} 当前有重新加载按钮 点击重新加载")
d(text="重新加载").click()
time.sleep(2)
continue
elif d(text="搜索").exists:
logger.error("当前网络连接异常 未找到重新加载按钮,重新点击搜索")
d(text="搜索").click()
time.sleep(2)
continue
return True
def human_like_scroll(d, keyword, client_ip, max_up=2, min_delay=2.0, max_delay=4.0):
screen_width, screen_height = d.window_size()
up_count = 0
down_count = 0
continuous_down = 0 # 连续下滑计数
random_down_threshold = random.randint(3, 5) # 触发上滑的门槛(3~5 次下滑后才允许上滑)
last_spider_count = None
last_change_time = time.time()
start_time = time.time()
max_nochange_time = 300
last_progress_time = time.time() # 只在 spider_count 变动时更新,用于 5 分钟强恢复
while True:
try:
# TODO: 退出条件 -> redis hget(f"xhs_app:{client_ip}:{keyword}", keyword) == 5 时 break
if not check_page_status(d, client_ip):
return False
if d(text="无更多内容").exists:
logger.success("采集完成 无更多内容")
return True
elif d(text="没有找到相关内容,换个词试试吧").exists:
logger.success("没有找到相关内容,换个词试试吧")
return True
try:
spider_count = redis_conn3.hget(f"xhs_app:{client_ip}", keyword)
# logger.success(f"xhs_app:{client_ip} keyword -> {keyword} spider_count -> {spider_count}", )
if spider_count is not None:
spider_count = int(spider_count)
except Exception as e:
print(f"[Redis异常] {e}")
spider_count = None
if spider_count == 5:
# logger.success(f"{keyword} 当前已拦截5次 退出滑动")
return True
if spider_count is not None:
if spider_count != last_spider_count:
# 正常进度,更新记录
last_spider_count = spider_count
last_change_time = time.time()
else:
# 计数没变化,超过15s → 认为卡住
if time.time() - last_change_time > 60:
# print("[卡顿检测] 页面长时间无变化,触发多次上滑+强力下滑容错")
# 连续上滑 2~3 次
for _ in range(random.randint(2, 3)):
d.swipe(
screen_width // 2,
int(screen_height * 0.6),
screen_width // 2,
int(screen_height * 0.8),
0.3
)
time.sleep(0.8)
# 强力下滑(90% 屏幕高度)
d.swipe(
screen_width // 2,
int(screen_height * 0.9),
screen_width // 2,
int(screen_height * 0.1),
0.5
)
time.sleep(3)
# 重置检测计时器
last_change_time = time.time() # 默认方向下滑
if time.time() - last_progress_time > max_nochange_time:
return False
# raise TimeoutError("spider_count 长时间无变化,触发强恢复")
direction = "down"
# 控制上滑逻辑:必须连续下滑 >= 随机门槛,且上滑次数不能超过 max_up
if continuous_down >= random_down_threshold and up_count < max_up and random.random() < 0.2:
direction = "up"
up_count += 1
continuous_down = 0 # 重置连续下滑计数
random_down_threshold = random.randint(3, 5) # 重新生成门槛
else:
direction = "down"
down_count += 1
continuous_down += 1
# ---- 改进的滑动区域计算(基于屏幕中间) ----
start_x = int(screen_width * 0.5 + random.randint(-50, 50)) # 中间 ±50px
start_y = int(screen_height * (0.5 + random.uniform(-0.2, 0.2))) # 中间 ±20% 高度
if direction == "down":
move_distance = int(screen_height * random.uniform(0.5, 0.7)) # 下滑距离 50%~70%
end_y = start_y - move_distance
else:
move_distance = int(screen_height * random.uniform(0.3, 0.5)) # 上滑保持中等力度
end_y = start_y + move_distance
# 边界保护,避免滑到最顶/最底
end_y = max(100, min(screen_height - 100, end_y))
duration = float(random.uniform(0.15, 0.3)) # 更快的滑动
# 执行滑动
try:
d.swipe(start_x, start_y, start_x, end_y, duration)
except Exception as e:
print(f"[滑动异常] {e}")
# 兜底强制下滑一次,避免卡死
d.swipe(screen_width // 2, int(screen_height * 0.8), screen_width // 2, int(screen_height * 0.2), 0.3)
continue
# 模拟浏览(拟人化操作)
action_chance = random.random()
if action_chance < 0.2:
# 偶尔长时间停留(认真看内容)
delay = random.uniform(5, 8)
# logger.info(f"[拟人操作] 长时间停留 {delay:.1f}s 模拟认真看内容")
time.sleep(delay)
elif action_chance < 0.3:
# 偶尔小幅度微调滑动
offset = random.randint(50, 120)
d.swipe(start_x, start_y, start_x, start_y - offset, random.uniform(0.1, 0.2))
time.sleep(random.uniform(1, 2))
elif action_chance < 0.4:
# 偶尔什么都不做,模拟发呆
delay = random.uniform(1, 3)
# logger.info(f"[拟人操作] 发呆中 {delay:.1f}s")
time.sleep(delay)
else:
# 正常停顿浏览(快速翻页)
delay = random.uniform(1, 2.0)
time.sleep(delay)
except Exception as e:
logger.error(e)
continue
def phone_operation(d, command):
d.press(command)
def do_search_scroll(d, task, client_ip):
if d(description="全部删除").exists:
d(description="全部删除").click()
logger.success("清空上次搜索内容")
if d(text="搜索, ").exists:
d(text="搜索, ").click()
for char in task:
d.send_keys(char)
time.sleep(random.uniform(0.1, 0.3))
if random.random() < 0.05:
d.send_keys(random.choice("abcdefghijklmnopqrstuvwxyz"))
time.sleep(0.1)
d.press("delete")
time.sleep(0.1)
d(text="搜索").click()
time.sleep(3)
if human_like_scroll(d, task, client_ip):
return True
return False
else:
dump_page(d, "")
logger.success("没有找到当前按钮")
class StateManager:
# 当前手机状态管理 检测账号是否异常,当前函数结束时候 需要将手机保持在 搜索页面中GlobalSearchActivity
def __init__(self, client_ip):
self.client_ip = client_ip
def check_status(self, d, client_ip):
info = d.app_current()
if info.get("package") == "com.xingin.xhs":
while 1:
info = d.app_current()
logger.warning(info)
activity = info.get("activity")
logger.success(f"{client_ip},{activity}")
if activity == "com.xingin.alioth.search.GlobalSearchActivity":
if d(text="服务器迷路了,晚点再试试吧").exists:
logger.error(f"{client_ip} 服务器迷路了,晚点再试试吧")
common_redis0.hset("xhs_device_status", client_ip, "0")
time.sleep(240)
continue
common_redis0.hset("xhs_device_status", client_ip, "1")
return True
elif activity in [".index.v2.IndexActivityV2", "com.xingin.xhs.index.v2.IndexActivityV2"]:
logger.success("当前手机页面处于首页,检测是否需要登陆,不需要登陆则跳转到搜索页面")
if d(text="登录发现更多精彩").exists and d(text="去登录").exists:
logger.error("当前账号掉线 重新登陆")
d(text="去登录").click()
Login(self.client_ip).login(d, client_ip)
elif d(text="账号下线提示"):
logger.error("当前弹窗登录掉线,点击重新登录")
d(text="重新登录").click()
time.sleep(3)
continue
else:
logger.success("当前无需登录,跳转到搜索页面")
if d(description="搜索").exists:
d(description="搜索").click()
time.sleep(3)
continue
elif activity in ["com.xingin.login.activity.WelcomeActivity",
"com.xingin.login.activity.LoginActivity",
"com.xingin.login.device.offline.DeviceOfflineRemindActivity",
"com.xingin.login.halfwelcome.HalfWelcomeActivity"]:
logger.success("当前正在登陆页面中,直接执行登陆程序")
Login(self.client_ip).login(d, client_ip)
elif activity == "com.xingin.reactnative.ui.WalifyReactTranslucentActivity":
logger.error("当前设备验证异常")
if d(text="当前账户异常, 允许启用本地生物验证").exists:
alert(f"小红书检测设备 {client_ip} 登陆异常 状态:当前账户异常, 允许启用本地生物验证,请及时查看")
else:
alert(f"小红书检测设备 {client_ip} 登陆异常 状态:未知状态,请及时查看")
common_redis0.hset("xhs_device_status", client_ip, "0")
return False
elif activity == "com.xingin.matrix.notedetail.NoteDetailActivity":
logger.warning(f"当前进入卡片详情页,点击退出当前页面")
d.click(44, 164)
time.sleep(3)
else:
logger.error(f"当前Activity 未处理:{activity}")
else:
while 1:
info = d.app_current()
logger.error(f'当前页面不在小红书中:{info.get("package")}')
for i in range(5):
phone_operation(d, 'back')
time.sleep(1)
DeviceManager.start_app(d)
time.sleep(5)
if info.get("package") == "com.xingin.xhs":
break
else:
logger.error(f"打开小红书失败,重新尝试,当前页面为:{info.get('package')}")
time.sleep(10)
continue
def check_collection_status(self, d):
client_status = redis_conn3.hget(f"xhs_app:status:{self.client_ip}", 'status')
if client_status == "infinity":
logger.success(f"{self.client_ip} 当前已经搜索超过上限,关闭系统等待明日采集")
DeviceManager.close_app(d)
sleep_until_next_8am()
logger.success(f"{self.client_ip} 当前完成休眠,开始继续运行")
redis_conn3.hset(f"xhs_app:status:{self.client_ip}", 'status', "success")
return False
return True
class DeviceManager:
"""设备管理"""
@staticmethod
def connect_phone(d):
d.app_start("com.xingin.xhs")
@staticmethod
def start_app(d):
d.app_start("com.xingin.xhs")
@staticmethod
def connect_app(ip_port):
print(ip_port)
result = subprocess.run(['adb', 'connect', ip_port],
capture_output=True, text=True, timeout=10)
logger.success(f'{result.stdout, result.stderr}')
@staticmethod
def close_app(d):
d.app_stop("com.xingin.xhs")
def check_activity(d):
"""检查当前 activity,返回状态 key"""
info = d.app_current()
if info.get("package") == "com.xingin.xhs":
activity = info.get("activity")
return activity
# com.xingin.xhs
else:
logger.error("当前不在小红书中,连续执行几次返回键")
DeviceManager.close_app(d)
time.sleep(5)
logger.error(f"当前页面异常: {info}")
return "react"
def sleep_until_next_8am():
"""休眠直到次日 8 点"""
now = datetime.datetime.now()
tomorrow = now + datetime.timedelta(days=1)
next_8am = datetime.datetime(year=tomorrow.year, month=tomorrow.month, day=tomorrow.day, hour=8, minute=0, second=0)
seconds = (next_8am - now).total_seconds()
logger.success(f"需要休眠 {seconds / 3600:.2f} 小时,直到 {next_8am}")
time.sleep(seconds)
def dump_page(d, name):
"""保存页面 XML,用于调试"""
xml = d.dump_hierarchy()
if not name:
name = "./xml"
else:
name = "./" + name
with open(f'{name}.xml', 'w', encoding='utf-8') as f:
f.write(xml)
def format_seconds(seconds: int) -> str:
h = seconds // 3600
m = (seconds % 3600) // 60
s = seconds % 60
return f"{h}h{m}m{s}s"
def get_next_runtime(index: int):
"""计算下一次运行时长(带错峰)"""
base_runtime = random.randint(5400, 7200) # 1.5~2 小时
offset = index * 600 + random.randint(-300, 300) # 每台错开 10 分钟,再加小随机
return max(3600, base_runtime + offset)
def auto_operation(d, keyword, client_ip):
retry = 0
max_retry = 3
state_mgr = StateManager(client_ip)
while True:
try:
if state_mgr.check_status(d, client_ip):
if do_search_scroll(d, keyword, client_ip):
break
logger.error(f"{client_ip} 当前查询异常,重试关键词 {keyword}")
continue
else:
set_device_status(client_ip, "0")
except TimeoutError as e:
retry += 1
logger.error(f"{keyword} 强恢复触发({retry}/{max_retry}):{e} -> 关闭 App 休息后继续")
DeviceManager.close_app(d)
sleep_time = random.randint(60, 120)
logger.success(f"休息 {sleep_time} 秒后继续当前关键词")
time.sleep(sleep_time)
DeviceManager.start_app(d)
time.sleep(5)
if retry >= max_retry:
break
def set_device_status(client_ip, status):
common_redis0.hset("xhs_device_status", client_ip, status)
def xxx(timestamp):
dt = datetime.datetime.fromtimestamp(timestamp)
# 格式化为年月日
return dt.strftime("%Y%m%d")
def worker(client_ip, index=0):
"""每台手机独立进程"""
# 初始化信息
DeviceManager.connect_app(client_ip)
logger.success(client_ip)
d = u2.Device(client_ip)
# current_app = d.app_current()
# print(f"当前前台应用: {current_app}")
# dump_page(d,"./te")
# return
DeviceManager.close_app(d)
time.sleep(5)
DeviceManager.start_app(d)
time.sleep(5)
state_mgr = StateManager(client_ip)
# 初始状态检测 确认当前设备与帐号可用
if state_mgr.check_status(d, client_ip):
set_device_status(client_ip, "1")
# 初始化各种时间
base_runtime = random.randint(5400, 7200)
offset = index * 600 + random.randint(-300, 300)
rest_after = max(1800, base_runtime + offset) #
start_time = int(time.time())
spider_task_count = 0
while 1:
task = common_redis0.spop("xhs:keyword:package:m:ks")
if not task:
# logger.info(f"{device_ip} 当前暂无任务,休息 1s")
time.sleep(1)
continue
if "," in task or not task:
continue
logger.success(task)
if ":::" not in task:
continue
task, pt = task.split(":::")
status = common_redis0.sadd(f"xhs:keyword:package:m:ks:{xxx(time.time())}", task)
if status == 0:
logger.info(f"{task}今日已经完成采集")
continue
now = datetime.datetime.now()
# ---------- 夜间休眠逻辑 ----------
if 2 <= now.hour < 8:
DeviceManager.close_app(d)
tomorrow_8am = now.replace(hour=8, minute=0, second=0, microsecond=0)
if now.hour >= 8: # 万一跨天
tomorrow_8am += datetime.timedelta(days=1)
sleep_time = int((tomorrow_8am - now).total_seconds())
sleep_time += index * 300 + random.randint(-60, 60)
logger.success(f"{client_ip} 夜间休眠至早上8点,总休眠 {format_seconds(sleep_time)}")
time.sleep(sleep_time)
# 重新启动 app
spider_task_count = 0
rest_after = get_next_runtime(index)
start_time = int(time.time())
DeviceManager.start_app(d)
time.sleep(5)
spider_task_count = 0
continue
# ---------- 白天运行逻辑 ----------
elapsed = int(time.time() - start_time)
if elapsed > rest_after:
DeviceManager.close_app(d)
sleep_time = random.randint(1200, 3600)
logger.success(f"{client_ip} 白天休息 {format_seconds(sleep_time)}")
time.sleep(sleep_time)
# 重置计时器
rest_after = get_next_runtime(index)
start_time = int(time.time())
DeviceManager.start_app(d)
time.sleep(5)
# ---------- 采集量过大逻辑 ----------
if spider_task_count > 280:
logger.success(f"{client_ip} 当前搜索量大于280,立即结束今日采集并休眠到次日 8 点")
DeviceManager.close_app(d)
tomorrow_8am = now.replace(hour=8, minute=0, second=0, microsecond=0)
if now.hour >= 8:
tomorrow_8am += datetime.timedelta(days=1)
sleep_time = int((tomorrow_8am - now).total_seconds())
sleep_time += index * 300 + random.randint(-60, 60)
logger.success(f"{client_ip} 夜间休眠至早上8点,总休眠 {format_seconds(sleep_time)}")
time.sleep(sleep_time)
# 重置
spider_task_count = 0
rest_after = get_next_runtime(index)
start_time = int(time.time())
DeviceManager.start_app(d)
# 正常操作
redis_conn3.hset(f"xhs_app:{client_ip}", task, '0')
redis_conn3.hset(f"xhs_app:{client_ip}:{task}", task, "1")
auto_operation(d, task, client_ip)
spider_task_count += 1
logger.info(f"{client_ip} {task} 已完成 任务总量 -> {spider_task_count}")
timeSleep = random.randint(3, 8)
time.sleep(timeSleep)
else:
logger.error(f"{client_ip} 当前设备无法使用 ")
return
def main():
phone_num = len(search_clientip)
processes = []
for idx, ip in enumerate(search_clientip):
p = multiprocessing.Process(target=worker, args=(ip, idx))
p.start()
processes.append(p)
for p in processes:
p.join()
if __name__ == '__main__':
main()
import asyncio
import json
import os
import random
import re
import time
import requests
from playwright.async_api import async_playwright, TimeoutError
from loguru import logger
from pymysql import InternalError
from redis.asyncio import Redis
common_redis0 = Redis(host='172.16.0.24', password="aiyingli@@123", port=6379, db=0, decode_responses=True)
common_redis2 = Redis(host='172.16.0.24', password="aiyingli@@123", port=6379, db=2, decode_responses=True)
common_redis3 = Redis(host='172.16.0.24', password="aiyingli@@123", port=6379, db=3, decode_responses=True)
import pymysql
from pymysql.err import OperationalError
class SimpleMySQL:
"""极简查询封装:只支持 SELECT * … WHERE ..."""
def __init__(self, charset="utf8mb4"):
self.cfg = dict(host="tenant-2101894307-cn-beijing-public.bytehouse.volces.com", port=3306, user="bytehouse",
password="m1wUyPHX0H:JQDqesXaoc", db="douchacha_data", charset=charset,
cursorclass=pymysql.cursors.DictCursor,
autocommit=True)
self._conn = None
self._connect()
# ---------- public ----------
def query(self, phone_num, start_time, deadline):
sql = f"SELECT * FROM recv_sms WHERE phone_num = {phone_num} AND recv_time >= {start_time} AND recv_time <= {deadline}"
try:
return self._execute(sql)
except OperationalError as e: # 连接异常自动重连一次
print(e)
if e.args and e.args[0] in (2006, 2013):
self._reconnect()
return self._execute(sql)
raise
# ---------- private ----------
def _connect(self):
if self._conn:
self._conn.close()
self._conn = pymysql.connect(**self.cfg)
def _reconnect(self):
try:
self._connect()
except Exception as e:
raise RuntimeError(f"Reconnect failed: {e}") from e
def _execute(self, sql):
with self._conn.cursor() as cur:
cur.execute(sql)
return cur.fetchall()
def close(self):
self._conn.close()
def _ensure_conn(self):
try:
self._conn.ping(reconnect=True) # 如果断了会自动重连
except Exception as e:
logger.error(f"MySQL ping failed, reconnecting: {e}")
self._conn = self._connect() # 你自己封装的重连逻辑
def replace_into(self, table, item_list):
self._ensure_conn()
if not item_list:
return 0
try:
keys = list(item_list[0].keys())
cols = ", ".join(f"`{k}`" for k in keys)
placeholders = ", ".join(["%s"] * len(keys))
sql = f"REPLACE INTO `{table}` ({cols}) VALUES ({placeholders})"
# 处理特殊字符
def sanitize_value(value):
if value is None:
return None
if isinstance(value, str):
# 移除或转义可能引起问题的字符
return value.replace('`', '').replace('\\', '\\\\')
return value
values = [tuple(sanitize_value(item[k]) for k in keys) for item in item_list]
with self._conn.cursor() as cur:
cur.executemany(sql, values)
logger.success(f"********** {table} 共写入{len(item_list)}条数据 **********")
return len(values)
except Exception as e:
print(f"Error: {e}")
raise
async def alert(msg):
url = "https://open.feishu.cn/open-apis/bot/v2/hook/1d0aa56a-ed39-4128-b445-ba953b32444b"
payload = {
"msg_type": "text",
"content": {
"text": msg
}
}
try:
resp = requests.post(
url,
json=payload,
headers={"Content-Type": "application/json"},
timeout=10
)
resp.raise_for_status()
logger.info("Feishu alert sent, status=%s", resp.status_code)
except requests.RequestException as e:
logger.error("Feishu alert failed: %s", e)
account_list = ["15313110635"]
# 18731654852
# 全局变量
MAX_INTERCEPT_COUNT = 5 # 最多拦截5次
spider_task_count = 0
MAX_RETRIES = 3 # 最大重试次数
TIMEOUT = 60000 # 超时时间60秒
search_notes_count_lock = asyncio.Lock() # 计数器锁
search_notes_count = 0 # 重置为0开始计数
account_status = {}
async def human_like_scroll(page, scroll_times=2):
for _ in range(scroll_times):
await asyncio.sleep(random.random())
scroll_distance = random.randint(300, 800)
await page.mouse.wheel(0, scroll_distance)
await page.wait_for_timeout(random.randint(200, 600))
if random.random() > 0.7:
x = random.randint(100, 500)
y = random.randint(100, 800)
await page.mouse.move(x, y)
async def handle_response(response, page, db, context, cursor):
if "user/profile" in response.url:
# 检查是否为重定向响应
if response.status >= 300 and response.status < 400:
print(f"重定向响应: {response.status} -> {response.headers.get('location')}")
return # 跳过对重定向响应的处理
# 只有非重定向响应才尝试读取响应体
try:
text = await response.text()
data_json = extract_and_parse_json(text)
if data_json:
data = json.loads(data_json)
user = data.get("user")
userId = response.url.split("/")[-1].split("?")[0]
basicInfo = user.get("userPageData").get("basicInfo")
nickname = basicInfo.get("nickname")
reqId = basicInfo.get("redId")
notes = user.get("notes")[0]
status = await common_redis2.hget("xhs_app:user_collect", reqId)
logger.debug(f"{reqId} {nickname} {len(notes)} {status}")
if status:
logger.success("当前用户已收录过")
else:
logger.success("开始添加收录任务")
# 直接走app端进行视频列表收录
await common_redis2.sadd("xhs:keyword:package:us", f"{userId}:::{reqId}")
# 处理一份数据给后端
backend_dic = {}
# 处理用户
backend_dic["user_id"] = userId
backend_dic["user_red_id"] = reqId
backend_dic["user_nickname"] = nickname
backend_dic["user_cover"] = basicInfo.get("images")
backend_dic["user_gender"] = basicInfo.get("gender")
backend_dic["user_ipLocation"] = basicInfo.get("ipLocation")
backend_dic["user_desc"] = basicInfo.get("desc")
interactions = user.get("userPageData").get("interactions")
for i in interactions:
# if i.get("type") == "follows":
# backend_dic["user_follow_count"] = i.get("count")
if i.get("type") == "fans":
backend_dic["user_follow_count"] = i.get("count")
elif i.get("type") == "interaction":
backend_dic["user_interaction_count"] = i.get("count")
else:
logger.error("暂未处理")
logger.success(backend_dic)
await common_redis2.hset("xhs_app:backend_user_info", userId, json.dumps(backend_dic))
db.replace_into("ods_base_user_data_xhs", [backend_dic])
logger.success(f"当前用户 {nickname} 共有视频:{len(notes)}")
except Exception as e:
print(f"读取响应体失败: {e}")
async def launch_browser(account):
playwright = await async_playwright().start()
context = await playwright.chromium.launch(
headless=False,
args=[
"--window-size=800,600",
# "--start-maximized"
"--disable-gpu",
],
# proxy={
# "server": "http://36.137.241.163:16817",
# "username": "iprowq",
# "password": "yk2gbxo4"
# }
)
page = await context.new_page()
page.set_default_timeout(10000)
await page.add_init_script("""
Object.defineProperty(navigator, 'webdriver', {
get: () => undefined
});
window.navigator.chrome = { runtime: {} };
""")
# await page.route("**/*", lambda route: route.abort()
# if route.request.resource_type == "image"
# else route.continue_())
await asyncio.sleep(1) # 等待 profile 锁释放
return playwright, context, page
def extract_and_parse_json(html: str) -> str:
pattern = r'__INITIAL_STATE__\s*=\s*({[\s\S]*?})\s*;?\s*</script>'
match = re.search(pattern, html)
# 错误处理
if not match or len(match.groups()) < 1:
logger.success(html)
logger.error("未找到匹配的JSON数据")
return ""
# 2. 清理JSON字符串
json_str = match.group(1).replace("undefined", "null")
return json_str
async def search(account):
global account_status, search_notes_count, spider_task_count
account_status[account] = "online"
db = SimpleMySQL()
while True:
playwright, context, page = await launch_browser(account)
page.on("response", lambda response: asyncio.create_task(
handle_response(response, page, db, context, cursor)
))
cursor = False
while True:
user_info = await common_redis2.spop("xhs:app:user_monitor_realTime")
if not user_info:
# logger.error("当时暂无数据")
await asyncio.sleep(1)
continue
search_notes_count = 0
user_id ,xsec_token = user_info.split(":::")
try:
if user_id == "":
continue
logger.success(f"正在搜索 {user_id}")
# xsec_token = await common_redis2.srandmember("xhs_app:xsec_token")
# xsec_token = "ABXgk0-UXUQq7CEUn1mEJ4_GifzLK8asXU9P0rVSFRNiw="
url = f"https://www.xiaohongshu.com/user/profile/{user_id}?xsec_token={xsec_token}&xsec_source=pc_feed"
await page.goto(url)
await page.wait_for_selector(".user-name", state="attached", timeout=5000)
time.sleep(5)
except Exception as e:
logger.warning(f"{account} 数据加载失败,任务回收: {e}")
continue
spider_task_count += 1
logger.info(f"当前已完成词总量 -> {spider_task_count}")
async def main():
account_tasks = [search(acc) for acc in account_list]
await asyncio.gather(*account_tasks)
if __name__ == '__main__':
asyncio.run(main())
# 17701383975
<?xml version='1.0' encoding='UTF-8' standalone='yes' ?>
<hierarchy rotation="0">
<node index="0" text="" resource-id="" class="android.widget.FrameLayout" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[0,0][1080,89]" drawing-order="0" hint="">
<node index="1" text="" resource-id="com.android.systemui:id/scrim_behind" class="android.view.View" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[0,0][1080,89]" drawing-order="2" hint="" />
<node index="2" text="" resource-id="com.android.systemui:id/scrim_in_front" class="android.view.View" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[0,0][1080,89]" drawing-order="9" hint="" />
<node index="3" text="" resource-id="" class="android.view.View" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[0,0][1080,89]" drawing-order="11" hint="" />
<node index="4" text="" resource-id="com.android.systemui:id/status_bar_container" class="android.widget.FrameLayout" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[0,0][1080,89]" drawing-order="4" hint="">
<node index="0" text="" resource-id="com.android.systemui:id/status_bar" class="android.widget.FrameLayout" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[3,0][1080,86]" drawing-order="1" hint="">
<node index="0" text="" resource-id="com.android.systemui:id/phone_status_bar_contents_container" class="android.widget.LinearLayout" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[22,0][1064,86]" drawing-order="3" hint="">
<node index="0" text="" resource-id="com.android.systemui:id/clock_container" class="android.widget.FrameLayout" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[30,3][234,86]" drawing-order="1" hint="">
<node index="0" text="" resource-id="com.android.systemui:id/leftside" class="android.widget.LinearLayout" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[30,3][234,86]" drawing-order="1" hint="">
<node index="0" text="1:07" resource-id="com.android.systemui:id/clock" class="android.widget.TextView" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[30,3][114,86]" drawing-order="10" hint="" />
<node index="2" text="" resource-id="com.android.systemui:id/notification_icon_area" class="android.widget.FrameLayout" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[114,3][234,86]" drawing-order="12" hint="">
<node index="0" text="" resource-id="com.android.systemui:id/notification_icon_area_inner" class="android.widget.LinearLayout" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[114,3][234,86]" drawing-order="1" hint="">
<node index="0" text="" resource-id="com.android.systemui:id/notificationIcons" class="android.widget.FrameLayout" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[114,3][234,86]" drawing-order="1" hint="">
<node index="0" text="" resource-id="" class="android.widget.ImageView" package="com.android.systemui" content-desc="下载管理程序通知:mitmproxy-ca-cert.cer" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[114,26][164,62]" drawing-order="1" hint="" />
</node>
</node>
</node>
</node>
</node>
<node index="1" text="" resource-id="" class="android.widget.FrameLayout" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[234,3][850,86]" drawing-order="2" hint="" />
<node index="2" text="" resource-id="com.android.systemui:id/system_icon_area" class="android.widget.LinearLayout" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[850,3][1052,86]" drawing-order="3" hint="">
<node index="0" text="" resource-id="com.android.systemui:id/system_icons" class="android.widget.LinearLayout" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="true" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[850,14][1052,74]" drawing-order="1" hint="">
<node index="0" text="" resource-id="com.android.systemui:id/signal_cluster_view" class="android.widget.LinearLayout" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[850,14][968,74]" drawing-order="5" hint="">
<node index="0" text="" resource-id="com.android.systemui:id/signal_cluster" class="android.widget.LinearLayout" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="true" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[850,14][968,74]" drawing-order="1" hint="">
<node index="0" text="" resource-id="com.android.systemui:id/mobile_signal_group_dual_notch" class="android.widget.LinearLayout" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="true" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[850,14][860,74]" drawing-order="9" hint="">
<node index="0" text="" resource-id="com.android.systemui:id/mobile_combo" class="android.widget.LinearLayout" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[850,14][860,74]" drawing-order="1" hint="">
<node index="1" text="" resource-id="com.android.systemui:id/notch_carrier" class="android.widget.TextView" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[850,14][855,74]" drawing-order="2" hint="" />
<node index="2" text="" resource-id="com.android.systemui:id/mobile_type" class="android.widget.TextView" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[855,14][860,74]" drawing-order="3" hint="" />
</node>
</node>
<node index="3" text="" resource-id="com.android.systemui:id/no_sims" class="android.widget.ImageView" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[860,16][910,72]" drawing-order="10" hint="" />
<node index="4" text="" resource-id="com.android.systemui:id/wifi_combo" class="android.widget.FrameLayout" package="com.android.systemui" content-desc="WLAN 信号满格。" checkable="false" checked="false" clickable="false" enabled="true" focusable="true" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[910,16][968,72]" drawing-order="14" hint="">
<node index="0" text="" resource-id="com.android.systemui:id/wifi_signal" class="android.widget.ImageView" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[910,16][968,72]" drawing-order="1" hint="" />
<node index="1" text="" resource-id="com.android.systemui:id/wifi_inout" class="android.widget.ImageView" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[942,16][968,72]" drawing-order="3" hint="" />
</node>
</node>
</node>
<node index="1" text="" resource-id="com.android.systemui:id/battery" class="android.widget.LinearLayout" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="true" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[968,14][1052,74]" drawing-order="6" hint="">
<node index="0" text="" resource-id="" class="android.widget.FrameLayout" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[968,16][1052,72]" drawing-order="1" hint="">
<node index="0" text="" resource-id="com.android.systemui:id/battery_image" class="android.widget.ImageView" package="com.android.systemui" content-desc="正在充电,已完成百分之100。" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[968,16][1052,72]" drawing-order="1" hint="" />
<node index="1" text="100" resource-id="com.android.systemui:id/battery_digit" class="android.widget.TextView" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[988,16][1026,72]" drawing-order="3" hint="" />
</node>
</node>
</node>
</node>
</node>
</node>
</node>
</node>
<node index="0" text="" resource-id="" class="android.widget.FrameLayout" package="com.xingin.xhs" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[0,0][1080,2248]" drawing-order="0" hint="">
<node index="0" text="" resource-id="com.xingin.xhs:id/0_resource_name_obfuscated" class="android.widget.FrameLayout" package="com.xingin.xhs" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[0,0][1080,2248]" drawing-order="1" hint="">
<node index="0" text="" resource-id="" class="android.widget.LinearLayout" package="com.xingin.xhs" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[0,0][1080,2118]" drawing-order="1" hint="">
<node index="0" text="" resource-id="" class="android.widget.FrameLayout" package="com.xingin.xhs" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[0,0][1080,2118]" drawing-order="2" hint="">
<node index="0" text="" resource-id="com.xingin.xhs:id/0_resource_name_obfuscated" class="android.widget.LinearLayout" package="com.xingin.xhs" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[0,0][1080,2118]" drawing-order="1" hint="">
<node index="0" text="" resource-id="android:id/content" class="android.widget.FrameLayout" package="com.xingin.xhs" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[0,0][1080,2118]" drawing-order="2" hint="">
<node index="0" text="" resource-id="" class="android.view.ViewGroup" package="com.xingin.xhs" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[0,0][1080,2118]" drawing-order="1" hint="">
<node index="0" text="" resource-id="" class="android.widget.LinearLayout" package="com.xingin.xhs" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[151,915][929,1293]" drawing-order="1" hint="">
<node index="0" text="当前账号存在异常,请切换账号后重试" resource-id="com.xingin.xhs:id/0_resource_name_obfuscated" class="android.widget.TextView" package="com.xingin.xhs" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[206,970][874,1101]" drawing-order="1" hint="" />
<node index="1" text="" resource-id="" class="android.view.View" package="com.xingin.xhs" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[151,1156][929,1157]" drawing-order="2" hint="" />
<node index="2" text="" resource-id="" class="android.widget.LinearLayout" package="com.xingin.xhs" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[151,1157][929,1293]" drawing-order="3" hint="">
<node index="0" text="知道了" resource-id="com.xingin.xhs:id/0_resource_name_obfuscated" class="android.widget.TextView" package="com.xingin.xhs" content-desc="" checkable="false" checked="false" clickable="true" enabled="true" focusable="true" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[151,1157][539,1293]" drawing-order="1" hint="" />
<node index="1" text="" resource-id="" class="android.view.View" package="com.xingin.xhs" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[539,1185][540,1262]" drawing-order="2" hint="" />
<node index="2" text="去反馈" resource-id="com.xingin.xhs:id/0_resource_name_obfuscated" class="android.widget.TextView" package="com.xingin.xhs" content-desc="" checkable="false" checked="false" clickable="true" enabled="true" focusable="true" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[540,1157][929,1293]" drawing-order="3" hint="" />
</node>
</node>
</node>
</node>
</node>
</node>
</node>
</node>
</node>
<node index="0" text="" resource-id="" class="android.widget.LinearLayout" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[0,2118][1080,2248]" drawing-order="0" hint="">
<node index="0" text="" resource-id="com.android.systemui:id/rot0" class="android.widget.FrameLayout" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[0,2118][1080,2248]" drawing-order="1" hint="">
<node index="0" text="" resource-id="com.android.systemui:id/deadzone" class="android.view.View" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[0,2118][1080,2248]" drawing-order="3" hint="" />
<node index="1" text="" resource-id="com.android.systemui:id/nav_buttons" class="android.widget.LinearLayout" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[0,2118][1080,2248]" drawing-order="1" hint="">
<node index="0" text="" resource-id="com.android.systemui:id/start_padding" class="android.widget.FrameLayout" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[0,2118][233,2248]" drawing-order="1" hint="" />
<node index="1" text="" resource-id="com.android.systemui:id/recent_apps" class="android.widget.ImageView" package="com.android.systemui" content-desc="概览" checkable="false" checked="false" clickable="true" enabled="true" focusable="true" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[236,2118][401,2245]" drawing-order="2" hint="" />
<node index="2" text="" resource-id="com.android.systemui:id/home" class="android.widget.ImageView" package="com.android.systemui" content-desc="主屏幕" checkable="false" checked="false" clickable="true" enabled="true" focusable="true" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[460,2118][625,2245]" drawing-order="4" hint="" />
<node index="3" text="" resource-id="com.android.systemui:id/back" class="android.widget.ImageView" package="com.android.systemui" content-desc="返回" checkable="false" checked="false" clickable="true" enabled="true" focusable="true" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[684,2118][849,2245]" drawing-order="6" hint="" />
<node index="4" text="" resource-id="com.android.systemui:id/side_padding" class="android.widget.FrameLayout" package="com.android.systemui" content-desc="" checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false" scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true" bounds="[846,2118][1080,2248]" drawing-order="7" hint="" />
</node>
</node>
</node>
</hierarchy>
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment