如何将Beautiful Soup爬取的天气数据存入SQLite3数据库?
嘿,我来帮你一步步把爬取的BBC天气数据存入SQLite3数据库,其实整个流程很清晰,咱们拆解成几个简单步骤来做:
1. 导入必要的模块
你已经用到了requests和BeautifulSoup,现在只需要额外导入Python自带的sqlite3模块就行,不用额外安装:
import requests from bs4 import BeautifulSoup import sqlite3
2. 创建数据库连接和天气数据表
首先咱们要创建一个本地数据库文件(比如叫weather.db),然后设计一张存储一周天气的数据表。表的字段可以根据你爬取的内容来定,比如日期、最高气温、最低气温、天气状况这些核心信息:
def init_db(): # 连接数据库(文件不存在则自动创建) conn = sqlite3.connect('weather.db') cursor = conn.cursor() # 创建数据表,加判断避免重复创建报错 cursor.execute(''' CREATE TABLE IF NOT EXISTS weekly_weather ( id INTEGER PRIMARY KEY AUTOINCREMENT, date TEXT NOT NULL, max_temp INTEGER NOT NULL, min_temp INTEGER NOT NULL, weather_desc TEXT ) ''') conn.commit() conn.close()
调用一次init_db()就能完成数据库和表的初始化了。
3. 修改爬虫函数,把数据存入数据库
接下来咱们把你现有的weather_()函数改一改,爬取到数据后直接插入到数据库里。我先补全你没写完的爬虫逻辑(贴合BBC天气页面的常见结构),然后加入插入数据的代码:
def weather_(): # 先初始化数据库 init_db() page = requests.get("https://www.bbc.co.uk/weather/0/2643743") soup = BeautifulSoup(page.content, 'html.parser') # 找到一周天气的每日容器(如果页面结构更新,可通过浏览器开发者工具微调选择器) weekly_days = soup.find_all('div', {'data-component-id': 'forecast-day'}) conn = sqlite3.connect('weather.db') cursor = conn.cursor() for day in weekly_days: # 提取日期(比如"周一 10月23日") day_name = day.find('span', class_='wr-day-name').text.strip() day_date = day.find('span', class_='wr-date').text.strip() full_date = f"{day_name} {day_date}" # 提取最高/最低气温,去掉符号转成整数 max_temp = int(day.find('span', class_='wr-value--temperature--max').text.strip().replace('°', '')) min_temp = int(day.find('span', class_='wr-value--temperature--min').text.strip().replace('°', '')) # 提取天气描述 weather_desc = day.find('div', class_='wr-day__weather-type-description').text.strip() # 插入数据到数据库(用?占位符避免SQL注入) cursor.execute(''' INSERT INTO weekly_weather (date, max_temp, min_temp, weather_desc) VALUES (?, ?, ?, ?) ''', (full_date, max_temp, min_temp, weather_desc)) conn.commit() conn.close() print("一周天气数据已成功存入数据库!")
小提示:如果BBC页面的类名更新导致数据提取失败,你可以用浏览器的开发者工具重新查看元素的类名,调整对应的选择器就行。
4. 验证数据是否成功存入
写个小函数来查询数据库里的数据,确认是不是存进去了:
def check_weather_data(): conn = sqlite3.connect('weather.db') cursor = conn.cursor() cursor.execute('SELECT * FROM weekly_weather') all_data = cursor.fetchall() print("数据库中的天气数据:") for row in all_data: print(f"ID: {row[0]}, 日期: {row[1]}, 最高温: {row[2]}°C, 最低温: {row[3]}°C, 天气: {row[4]}") conn.close()
调用check_weather_data()就能看到所有存入的数据了。
最后给你两个小建议:
- 每次爬取前可以考虑清空旧数据(比如加个
DELETE FROM weekly_weather的语句),避免重复存储; - 用
with语句管理数据库连接更安全,比如with sqlite3.connect('weather.db') as conn:,这样不用手动关闭连接,程序会自动处理。
内容的提问来源于stack exchange,提问作者Adam Williams
相关产品推荐
相关产品推荐

