Python打造可点击百度搜索结果的GUI程序

想要用Python创建一个可以抓取百度搜索结果并以可点击链接展示的GUI程序吗?以下代码将帮助你实现这个目标:

import requests
from bs4 import BeautifulSoup
import time
import tkinter as tk
import webbrowser

def crawl_baidu(keyword):
    headers = {
        '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://www.baidu.com/s?wd={keyword}'
    time.sleep(0.5)  # 添加延迟
    response = requests.get(url, headers=headers)
    soup = BeautifulSoup(response.text, 'html.parser')

    results = []
    for result in soup.find_all('div', class_='result'):
        result_url = result.find('a')['href']
        results.append(result_url)

    return results

def open_url(url):
    webbrowser.open(url)

def search():
    keyword = entry.get()
    search_results = crawl_baidu(keyword)
    if len(search_results) > 0:
        for index, url in enumerate(search_results, start=1):
            result_text.insert(tk.END, f'{index}. ', 'index')
            result_text.insert(tk.END, url, 'link')
            result_text.tag_configure('link', foreground='blue', underline=True)
            result_text.tag_bind('link', '<Button-1>', lambda event, url=url: open_url(url))
            result_text.insert(tk.END, '
')
        result_text.insert(tk.END, '
')
    else:
        result_text.insert(tk.END, '没有搜索结果\n')

# 创建UI界面
window = tk.Tk()
window.title('百度搜索')
window.geometry('800x600')

label = tk.Label(window, text='请输入关键词:')
label.pack()

entry = tk.Entry(window)
entry.pack()

search_button = tk.Button(window, text='搜索', command=search)
search_button.pack()

scrollbar = tk.Scrollbar(window)
scrollbar.pack(side=tk.RIGHT, fill=tk.Y)

result_text = tk.Text(window, yscrollcommand=scrollbar.set)
result_text.pack(fill=tk.BOTH)

scrollbar.config(command=result_text.yview)

window.mainloop()

这段代码使用requests库抓取百度搜索结果页面,使用BeautifulSoup解析HTML,提取搜索结果链接,并利用tkinter库创建图形界面,将搜索结果以可点击超链接的方式展示给用户。用户点击链接后,程序会自动打开浏览器并跳转到对应网页。

代码亮点:

  • 使用requests库模拟浏览器发送请求,并设置User-Agent以避免被反爬虫机制拦截。
  • 使用BeautifulSoup库高效解析HTML,精准提取目标数据。
  • 使用tkinter库创建用户友好的图形界面,提升用户体验。
  • 将搜索结果以可点击超链接的方式展示,方便用户直接访问目标网页。
  • 代码结构清晰,易于理解和维护。

希望这段代码可以帮助你学习Python网页抓取和GUI编程的相关知识。

Python打造可点击百度搜索结果的GUI程序

原文地址: https://www.cveoy.top/t/topic/rxI 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录