python项目练习——15.网页爬虫应用程序

这个项目可以让用户输入一个网址,然后爬取该网页的内容,并提取出其中的信息,比如标题、链接等。这个项目涉及到网络请求、HTML 解析、数据提取等方面的技术。

代码示例:

import tkinter as tk # 导入 Tkinter 库

from tkinter import scrolledtext # 导入 scrolledtext 模块

import requests # 导入 requests 库

from bs4 import BeautifulSoup # 导入 BeautifulSoup 库

class WebScraperApp:

def init(self, master):

self.master = master

self.master.title('简易网页爬虫')

创建界面组件

self.label_url = tk.Label(master, text='网址:')

self.label_url.grid(row=0, column=0)

self.entry_url = tk.Entry(master)

self.entry_url.grid(row=0, column=1)

self.btn_scrape = tk.Button(master, text='爬取', command=self.scrape_website)

self.btn_scrape.grid(row=0, column=2)

self.textbox = scrolledtext.ScrolledText(master, width=40, height=10)

self.textbox.grid(row=1, column=0, columnspan=3)

def scrape_website(self):

url = self.entry_url.get()

if url:

try:

response = requests.get(url) # 发送请求获取网页内容

soup = BeautifulSoup(response.text, 'html.parser') # 使用 BeautifulSoup 解析网页内容

提取网页标题并显示在文本框中

title = soup.title.string.strip()

self.textbox.insert(tk.END, f'标题: {title}\n')

提取所有链接并显示在文本框中

links = soup.find_all('a')

for link in links:

href = link.get('href')

self.textbox.insert(tk.END, f'链接: {href}\n')

except Exception as e:

self.textbox.insert(tk.END, f'爬取网页失败: {e}\n')

else:

self.textbox.insert(tk.END, '请输入网址\n')

if name == 'main':

root = tk.Tk() # 创建主窗口

app = WebScraperApp(root) # 创建网页爬虫应用程序实例

root.mainloop() # 运行主事件循环

代码逻辑分析:

使用 Tkinter 库创建了一个简单的图形界面网页爬虫应用程序。用户可以在输入框中输入网址,点击爬取按钮将网页内容爬取下来,并提取其中的标题和链接,并在界面上显示出来。网页内容通过 requests 库发送请求获取,然后通过 BeautifulSoup 库解析 HTML 内容提取信息。

相关推荐
zone77394 小时前
001:简单 RAG 入门
后端·python·面试
F_Quant4 小时前
🚀 Python打包踩坑指南:彻底解决 Nuitka --onefile 配置文件丢失与重启报错问题
python·操作系统
允许部分打工人先富起来5 小时前
在node项目中执行python脚本
前端·python·node.js
IVEN_5 小时前
Python OpenCV: RGB三色识别的最佳工程实践
python·opencv
haosend6 小时前
AI时代,传统网络运维人员的转型指南
python·数据网络·网络自动化
曲幽6 小时前
不止于JWT:用FastAPI的Depends实现细粒度权限控制
python·fastapi·web·jwt·rbac·permission·depends·abac
IVEN_1 天前
只会Python皮毛?深入理解这几点,轻松进阶全栈开发
python·全栈
Ray Liang1 天前
用六边形架构与整洁架构对比是伪命题?
java·python·c#·架构设计
AI攻城狮1 天前
如何给 AI Agent 做"断舍离":OpenClaw Session 自动清理实践
python
千寻girling1 天前
一份不可多得的 《 Python 》语言教程
人工智能·后端·python