# coding: utf-8
import webbrowser
import bs4
import tkinter as tk
import requests
head = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3"
}
def search():
result = search_bar.get("1.0", "end").strip()
if result == '':
text_bar.delete('1.0', tk.END)
text_bar.insert('1.0', '您未输入内容')
return
text_bar.delete('1.0', tk.END)
text_bar.insert('1.0', '正在搜索...')
url = "https://baike.baidu.com/item/" + result
try:
res = requests.get(url, headers=head)
res.raise_for_status()
except requests.RequestException as e:
text_bar.delete('1.0', tk.END)
text_bar.insert('1.0', '请求失败, 请检查你的网络连接或者权限')
return
soup = bs4.BeautifulSoup(res.text, "lxml")
search_results = soup.find_all('span', class_='text_ki2nn') # 更改变量名以避免与函数参数result冲突
search_string = ''.join(tag.get_text() for tag in search_results)
text_bar.delete('1.0', tk.END)
text_bar.insert('1.0', search_string)
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_button = tk.Button(main, width=8, height=2, command=search)
about_button = tk.Button(main, width=8, height=1, command=about)
text_bar = tk.Text(main, width=84, height=10, font=("微软雅黑", 10))
search_button["text"] = "搜索"
about_button["text"] = "关于"
# 使用绝对布局
search_bar.place(x=10, y=23)
search_button.place(x=620, y=15)
about_button.place(x=930, y=5)
text_bar.place(x=10, y=70)
main.mainloop() # 保持窗口运行
这段代码想要实现一个“搜索”的效果,用户在search_bar搜索并点search_button后会在text_bar展示在百度百科爬取对应内容并进行处理的结果,但是往往运行后“搜索”第一次后就会占用大量资源(第一次“搜索”时并没有)导致程序未响应
Python 3.12 Subline Build 4192 库都安装了