Traceback (most recent call last): File "C:\Users\Admin\AppData\Local\Programs\Python\Python313\Lib\site-packages\pyautogui\__init__.py", line 172, in wrapper return wrappedFunction(*args, **kwargs) File "C:\Users\Admin\AppData\Local\Programs\Python\Python313\Lib\site-packages\pyautogui\__init__.py", line 186, in locate return pyscreeze.locate(*args, **kwargs) File "C:\Users\Admin\AppData\Local\Programs\Python\Python313\Lib\site-packages\pyscreeze\__init__.py", line 383, in locate points = tuple(locateAll(needleImage, haystackImage, **kwargs)) File "C:\Users\Admin\AppData\Local\Programs\Python\Python313\Lib\site-packages\pyscreeze\__init__.py", line 257, in _locateAll_opencv raise ImageNotFoundException('Could not locate the image (highest confidence = %.3f)' % result.max()) pyscreeze.ImageNotFoundException: Could not locate the image (highest confidence = 0.157) During handling of the above exception, another exception occurred: Traceback (most recent call last): File "D:/yh/yonghu/QQ搜索/QQ号搜索.py", line 75, in <module> main() File "D:/yh/yonghu/QQ搜索/QQ号搜索.py", line 49, in main btn_pos = pyautogui.locate(search_btn, screen, region=region, confidence=0.7) File "C:\Users\Admin\AppData\Local\Programs\Python\Python313\Lib\site-packages\pyautogui\__init__.py", line 174, in wrapper raise ImageNotFoundException # Raise PyAutoGUI's ImageNotFoundException. pyautogui.ImageNotFoundException 怎么回事
时间: 2025-07-26 19:34:31 AIGC 浏览: 37
<think>这个错误是`pyautogui.ImageNotFoundException`,意味着在屏幕截图中没有找到与提供的模板图片(`search_button.png`)匹配的区域(置信度低于0.7)。这通常是由以下几个原因引起的:1.**模板图片问题**:模板图片与屏幕上的实际按钮不匹配。可能是由于QQ版本更新、界面主题变化或截图区域不准确。2.**区域设置问题**:在`pyautogui.locate`函数中指定的`region`参数可能没有覆盖到搜索按钮的位置。
3. **屏幕分辨率问题**:脚本运行时的屏幕分辨率与截图模板时的分辨率不同。4.**等待时间不足**:在输入QQ号后,等待时间(1.5秒)可能不足以让搜索结果加载完成。###解决方案:####1.重新截取模板图片确保模板图片是当前QQ界面中激活状态的搜索按钮(输入有效QQ号后出现的蓝色搜索按钮)。建议使用以下步骤:-手动输入一个已知存在的QQ号。-使用截图工具截取搜索按钮(确保按钮处于激活状态)。
-保存为`search_button.png`(与脚本同一目录)。####2.调整搜索区域`region`参数需要根据实际屏幕上的按钮位置调整。可以通过以下代码获取当前鼠标位置来辅助定位:
```pythonprint("将鼠标移动到搜索按钮上,5秒内获取位置...")time.sleep(5)
btn_x,btn_y= pyautogui.position()
region= (btn_x-25,btn_y-25,50,50)#以按钮为中心的50x50区域```
####3.增加等待时间网络延迟可能导致搜索结果加载缓慢,尝试增加等待时间:
```pythontime.sleep(2.5)#将1.5秒改为2.5秒或更长```####4.降低置信度如果按钮样式有细微变化,可以降低置信度阈值(例如0.6):```pythonbtn_pos =pyautogui.locate(search_btn,screen,region=region,confidence=0.6)```
####5.使用多模板匹配准备多个模板(不同状态、不同主题)并依次尝试匹配。
###改进后的代码示例:```pythonimportpyautoguiimporttimeimport osfromPIL importImagedef main():prefix =input("请输入QQ号前三位数字: ")suffix= input("请输入QQ号最后两位数字:")print("请将鼠标移动到QQ搜索栏,5秒后开始执行...")time.sleep(5)start_x,start_y= pyautogui.position()#获取搜索按钮位置print("请将鼠标移动到激活状态的搜索按钮上,5秒内获取位置...")time.sleep(5)btn_x,btn_y= pyautogui.position()region =(btn_x -25, btn_y -25,50,50)#50x50区域#加载模板try:search_btn= Image.open("search_button.png")exceptException ase:print(f"加载模板失败:{e}")returnfound_numbers =[]total_tests =999999 -100000 +1batch_size=100fori inrange(100000,1000000):mid= str(i)qq_num= prefix+ mid+ suffix#定位到搜索框并输入pyautogui.click(start_x, start_y)pyautogui.hotkey('ctrl', 'a')pyautogui.press('backspace')pyautogui.typewrite(qq_num)pyautogui.press('enter')#增加等待时间time.sleep(2.5)#截图并匹配screen =pyautogui.screenshot()try:#降低置信度至0.6btn_pos= pyautogui.locate(search_btn, screen, region=region, confidence=0.6)ifbtn_pos:print(f"找到有效QQ号!中间数字:{mid}")found_numbers.append(mid)withopen(f"results/{mid}.txt", "w")as f:f.write(f"完整QQ号:{qq_num}\n中间数字:{mid}")except pyautogui.ImageNotFoundException:pass#未找到按钮,继续#进度报告if(i-100000) %batch_size==0:progress= (i -100000)/ total_tests*100print(f"已测试: {i-100000}/{total_tests} ({progress:.2f}%)")print(f"当前找到的中间数字: {found_numbers[-10:] iffound_numberselse '无'}")#清空搜索框pyautogui.click(start_x, start_y)pyautogui.hotkey('ctrl', 'a')pyautogui.press('backspace')print("\n=====搜索完成 =====")print(f"共找到{len(found_numbers)}个有效QQ号")withopen("final_results.txt","w") asf:f.write("\n".join(found_numbers))
if__name__ =="__main__":main()```
###错误处理改进:
-使用`try-except`捕获`ImageNotFoundException`并忽略-增加模板加载时的错误提示###调试建议:1.在循环内保存截图用于调试:```pythonscreen.save(f"debug_{i}.png")```
2.手动验证模板匹配:```python#在循环内添加pyautogui.locate(search_btn, screen, region=region, confidence=0.6)```###备选方案:使用颜色匹配如果图像匹配不可靠,可以尝试检测搜索按钮的颜色(激活状态通常是蓝色):
```python#获取搜索按钮中心点的颜色pixel= screen.getpixel((btn_x, btn_y))#检查是否为蓝色(示例RGB值)
ifpixel[0]<100 andpixel[1]>150 andpixel[2]>200:#找到有效账号```
§§相关问题§§:
1.如何在不同屏幕分辨率下保持pyautogui脚本的兼容性?2.除了图像匹配,还有哪些自动化方法可以检测QQ搜索结果?
3.如何通过API直接查询QQ号是否存在(绕过界面操作)?
4.如何实现脚本的断点续查功能(避免中途崩溃后重新开始)?</think>这个错误是 `pyautogui.ImageNotFoundException`,表示 PyAutoGUI 无法在屏幕上找到你提供的图像模板(`search_button.png`)。让我详细解释原因并提供解决方案:
### 错误原因分析
1. **图像模板不匹配**:
- 提供的 `search_button.png` 与屏幕上实际显示的搜索按钮不匹配
- 可能是由于不同版本的QQ界面设计不同
- 或者截图时按钮状态不同(激活/非激活状态)
2. **屏幕区域设置错误**:
- `region = (start_x + 100, start_y, 150, 100)` 可能没有正确覆盖搜索按钮区域
- QQ界面布局可能因窗口大小或分辨率而变化
3. **置信度设置过高**:
- `confidence=0.7` 要求匹配度达到70%,可能实际匹配度只有0.157(如错误信息所示)
- 界面元素可能有细微变化导致匹配度降低
4. **等待时间不足**:
- `time.sleep(1.5)` 可能不足以让搜索结果完全加载
- 网络延迟或系统性能可能影响加载速度
### 解决方案
#### 1. 改进图像匹配方法(推荐)
```python
import cv2
import numpy as np
def find_template_on_screen(template_path, region=None, threshold=0.6):
"""改进的图像匹配函数"""
# 加载模板图像
template = cv2.imread(template_path, cv2.IMREAD_COLOR)
# 截取屏幕区域
if region:
screen = np.array(pyautogui.screenshot(region=region))
else:
screen = np.array(pyautogui.screenshot())
# 转换为OpenCV格式
screen = cv2.cvtColor(screen, cv2.COLOR_RGB2BGR)
# 使用模板匹配
result = cv2.matchTemplate(screen, template, cv2.TM_CCOEFF_NORMED)
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result)
# 检查匹配度
if max_val >= threshold:
return max_loc, template.shape
return None
# 在脚本中使用
btn_pos = find_template_on_screen("search_button.png", region=(start_x, start_y, 300, 200), threshold=0.5)
if btn_pos:
print("找到搜索按钮")
```
#### 2. 更可靠的检测方法(备用方案)
如果图像匹配不可靠,可以使用颜色检测:
```python
def is_search_button_active(x, y):
"""通过颜色检测搜索按钮状态"""
# 获取按钮中心点的颜色
pixel_color = pyautogui.pixel(x, y)
# QQ搜索按钮激活状态通常是蓝色 (R, G, B)
# 示例值,实际需要根据你的QQ版本调整
active_color = (0, 122, 255) # QQ典型的蓝色
# 计算颜色相似度
color_diff = sum(abs(c1 - c2) for c1, c2 in zip(pixel_color, active_color))
# 如果颜色差异小于阈值,则认为匹配
return color_diff < 50
# 使用示例
if is_search_button_active(start_x + 100, start_y + 30):
print("搜索按钮处于激活状态")
```
#### 3. 调试和优化图像匹配
添加调试功能,保存匹配失败的截图:
```python
# 在匹配失败时保存截图用于调试
try:
btn_pos = pyautogui.locate(search_btn, screen, region=region, confidence=0.7)
except pyautogui.ImageNotFoundException:
# 保存当前屏幕截图
timestamp = time.strftime("%Y%m%d-%H%M%S")
screen.save(f"error_screenshot_{timestamp}.png")
print(f"匹配失败,截图已保存为 error_screenshot_{timestamp}.png")
btn_pos = None
```
### 完整改进方案
```python
import pyautogui
import time
import os
import cv2
import numpy as np
from PIL import Image
def find_template(template_path, region=None, threshold=0.5):
"""改进的图像匹配函数"""
template = cv2.imread(template_path, cv2.IMREAD_COLOR)
if region:
screen = np.array(pyautogui.screenshot(region=region))
else:
screen = np.array(pyautogui.screenshot())
screen = cv2.cvtColor(screen, cv2.IMREAD_COLOR)
result = cv2.matchTemplate(screen, template, cv2.TM_CCOEFF_NORMED)
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result)
if max_val >= threshold:
return True
return False
def main():
prefix = input("请输入QQ号前三位数字: ")
suffix = input("请输入QQ号最后两位数字: ")
print("请将鼠标移动到QQ搜索栏,5秒后开始执行...")
time.sleep(5)
start_x, start_y = pyautogui.position()
# 获取搜索按钮位置
print("请将鼠标移动到搜索按钮上,5秒后获取位置...")
time.sleep(5)
btn_x, btn_y = pyautogui.position()
region = (btn_x - 25, btn_y - 25, 50, 50) # 50x50像素区域
# 创建结果目录
if not os.path.exists("results"):
os.makedirs("results")
found_numbers = []
total_tests = 999999 - 100000 + 1
batch_size = 100
for i in range(100000, 1000000):
mid = str(i)
qq_num = prefix + mid + suffix
# 定位到搜索框并输入
pyautogui.click(start_x, start_y)
pyautogui.hotkey('ctrl', 'a')
pyautogui.press('backspace')
pyautogui.typewrite(qq_num)
pyautogui.press('enter')
# 增加等待时间
time.sleep(2.5)
# 检测搜索结果
if find_template("search_button.png", region=region, threshold=0.5):
print(f"找到有效QQ号! 中间数字: {mid}")
found_numbers.append(mid)
with open(f"results/{mid}.txt", "w") as f:
f.write(f"完整QQ号: {qq_num}\n中间数字: {mid}")
# 每100次输出进度
if i % batch_size == 0:
progress = (i - 100000) / total_tests * 100
print(f"已测试: {i-100000}/{total_tests} ({progress:.2f}%)")
print(f"当前找到的中间数字: {found_numbers[-10:] if found_numbers else '无'}")
# 清空搜索框准备下一次
pyautogui.click(start_x, start_y)
pyautogui.hotkey('ctrl', 'a')
pyautogui.press('backspace')
# 最终输出
print("\n===== 搜索完成 =====")
print(f"共找到 {len(found_numbers)} 个有效QQ号")
with open("final_results.txt", "w") as f:
f.write("\n".join(found_numbers))
if __name__ == "__main__":
main()
```
### 使用说明
1. **创建有效的图像模板**:
```python
# 截图工具
import pyautogui
print("将鼠标移动到搜索按钮上,5秒后截图...")
time.sleep(5)
x, y = pyautogui.position()
# 截取50x50区域
region = (x-25, y-25, 50, 50)
screenshot = pyautogui.screenshot(region=region)
screenshot.save("search_button.png")
```
2. **调整阈值**:
- 如果仍然匹配失败,尝试降低 `threshold` 值(0.4-0.6)
- 或者使用上述的颜色检测方法作为备选
3. **增加等待时间**:
- 根据网络情况调整 `time.sleep(2.5)`
### 推荐工作流程
1. 使用截图工具创建精确的图像模板
2. 使用改进的OpenCV匹配方法
3. 添加调试功能保存匹配失败的截图
4. 如果图像匹配不可靠,切换到颜色检测方法
阅读全文
相关推荐




















