import requests
import tkinter as tk
import bs4
import webbrowser
import threading
import time
def getTextInput():
return search_bar.get("1.0", "end").strip()
def search():
threading.Thread(target=search_in_thread, daemon=True).start()
def search_in_thread():
result = getTextInput()
if not result:
return
text_bar.delete('1.0', tk.END)
text_bar.insert('1.0', '正在搜索...')
head = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"
}
url = f"https://baike.baidu.com/item/{result}"
try:
res = requests.get(url, headers=head, timeout=5)
res.raise_for_status()
except requests.RequestException as e:
text_bar.delete('1.0', tk.END)
text_bar.insert('1.0', f"请求失败: {e}")
return
res.encoding = res.apparent_encoding
soup = bs4.BeautifulSoup(res.text, "lxml")
lab = soup.find_all('span', class_='text_ki2nn')
string = "".join(i.get_text() for i in lab)
# 在 Tkinter 线程中更新 UI
text_bar.after(0, lambda: update_text_bar(string))
def update_text_bar(text):
text_bar.delete('1.0', tk.END)
text_bar.insert('1.0', text if text else '未找到相关信息')
def about():
webbrowser.open("about.py")
main = tk.Tk()
main.title('智能搜索器')
main.geometry("1000x500+10+10")
search_bar = tk.Text(main, width=50, height=1, font=("微软雅黑", 16))
search_botton = tk.Button(main, width=8, height=2)
about_botton = tk.Button(main, width=8, height=1)
text_bar = tk.Text(main, width=84, height=10, font=("微软雅黑", 10)) # 文本框
search_botton["text"] = "搜索"
about_botton["text"] = "关于"
# 绝对布局
search_bar.place(x=10, y=23)
search_botton.place(x=620, y=15)
about_botton.place(x=930, y=5)
text_bar.place(x=10, y=70)
search_botton.config(command=search)
about_botton.config(command=about)
main.mainloop()
这段代码想要实现一个在百度百科爬取信息并进行类似搜索的效果
但是遇到了未响应的问题
一般进行一次“搜索”后,就能在任务管理器看到CPU资源占用率暴涨,程序也开始未响应,所以无法进行下一次“搜索”
简单分析后发现应该是解析和查找方面的问题,但是始终不知道怎么办,问了GPT 4o 但是他要不让他丧失了原来的功能,要不没有达到解决问题的效果

环境:Python 3.12.2 ,编辑器:Subline Text build 4192