python3.9版本下编程一个例子用tkinter设计系统界面,将所输入的网站进行数据爬取(例如标题与链接),并将所爬取到的内容存入数据库中,从数据库中读取数据进行处理,用matplotlib实现数据绘图
时间: 2024-02-13 11:06:16 浏览: 15
好的,我可以为您提供一个简单的示例代码,用于实现您所描述的功能。请注意,以下代码仅供参考,您需要根据实际情况进行修改和调整。
```python
import tkinter as tk
import requests
from bs4 import BeautifulSoup
import sqlite3
import matplotlib.pyplot as plt
# 创建GUI界面
root = tk.Tk()
root.title("网站数据爬取")
root.geometry("400x300")
# 创建输入框和按钮
url_label = tk.Label(root, text="请输入网址:")
url_label.pack()
url_entry = tk.Entry(root)
url_entry.pack()
def scrape_data():
# 获取输入框中的网址
url = url_entry.get()
# 发送请求并解析页面
response = requests.get(url)
soup = BeautifulSoup(response.content, "html.parser")
# 获取页面中的标题和链接
titles = []
links = []
for item in soup.find_all("a"):
title = item.get("title")
link = item.get("href")
if title is not None and link is not None:
titles.append(title)
links.append(link)
# 将数据存入数据库中
conn = sqlite3.connect("data.db")
c = conn.cursor()
c.execute("CREATE TABLE IF NOT EXISTS websites (title TEXT, link TEXT)")
for i in range(len(titles)):
c.execute("INSERT INTO websites VALUES (?, ?)", (titles[i], links[i]))
conn.commit()
conn.close()
# 从数据库中读取数据并绘制图表
conn = sqlite3.connect("data.db")
c = conn.cursor()
c.execute("SELECT COUNT(*), title FROM websites GROUP BY title")
rows = c.fetchall()
conn.close()
counts = [row[0] for row in rows]
titles = [row[1] for row in rows]
plt.bar(titles, counts)
plt.xticks(rotation=90)
plt.show()
scrape_button = tk.Button(root, text="爬取数据并绘制图表", command=scrape_data)
scrape_button.pack()
root.mainloop()
```
这个程序会创建一个简单的GUI界面,包含一个输入框和一个按钮。当用户输入网址并点击按钮时,程序会发送请求并解析页面,获取页面中的标题和链接,并将这些数据存入SQLite数据库中。接着,程序会从数据库中读取数据并绘制图表,展示每个标题出现的次数。请注意,您需要在程序中修改数据库文件名和表名,以适配实际情况。