数据采集第二次作业
作业1
在中国气象网( http://www.weather.com.cn )给定城市集【3-5个城市】的7日天气预报,并保存在数据库
代码及结果:
import requests
from bs4 import BeautifulSoup
import sqlite3
import time
import random
import os
# 1. 定义要爬取的城市及对应代码
CITIES = {
"北京": "101010100",
"上海": "101020100",
"广州": "101280101",
"福州": "101230101",
"成都": "101270101"
}
# 2. 模拟浏览器访问,防止被反爬拦截
HEADERS = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36",
"Referer": "http://www.weather.com.cn/"
}
def get_weather(city_name, city_code):
"""获取单个城市的7日天气数据"""
url = f"http://www.weather.com.cn/weather/{city_code}.shtml"
print(f"正在爬取:{city_name} 的天气预报...")
all_weather_data = []
try:
resp = requests.get(url, headers=HEADERS, timeout=10)
resp.encoding = 'utf-8'
soup = BeautifulSoup(resp.text, 'html.parser')
# 找到包含7天预报的容器
ul_weather = soup.find("ul", class_="t")
if not ul_weather:
print(f"警告:未在页面中找到 {city_name} 的7天预报区域。")
return all_weather_data
lis = ul_weather.find_all("li")
for li in lis:
try:
# 解析日期
date_tag = li.find("h1")
date = date_tag.get_text(strip=True) if date_tag else "未知"
# 解析天气(如:晴、多云)
weather_tag = li.find("p", class_="wea")
weather = weather_tag.get_text(strip=True) if weather_tag else "未知"
# 解析温度
tem_div = li.find("p", class_="tem")
low_temp = "无"
high_temp = ""
if tem_div:
# 最低温通常在 i 标签
low_tag = tem_div.find("i")
low_temp = low_tag.get_text(strip=True) if low_tag else "无"
# 最高温通常在 span 标签
high_tag = tem_div.find("span")
high_temp = high_tag.get_text(strip=True) if high_tag else ""
else:
# 兜底方案:如果找不到 class="tem" 的容器,直接找 p.tem i
low_tags = li.select("p.tem i")
if low_tags: low_temp = low_tags[0].get_text(strip=True)
high_tags = li.select("p.tem span")
if high_tags: high_temp = high_tags[0].get_text(strip=True)
# 解析风向和风力
wind_tag = li.find("p", class_="win")
wind_info = "未知"
if wind_tag:
# 获取风向
em_tag = wind_tag.find("em")
if em_tag and em_tag.get("title"):
wind_dir = em_tag["title"]
elif em_tag:
wind_dir = em_tag.get_text(strip=True)
else:
wind_dir = ""
# 获取风力
i_tag = wind_tag.find("i")
wind_level = i_tag.get_text(strip=True) if i_tag else ""
wind_info = f"{wind_dir} {wind_level}"
# 组装单条数据
all_weather_data.append({
"city": city_name,
"date": date,
"weather": weather,
"high_temp": high_temp,
"low_temp": low_temp,
"wind_info": wind_info
})
except Exception as e:
print(f" > 解析 {city_name} 单日天气数据时发生错误:{e}")
continue
except Exception as e:
print(f"请求 {city_name} 页面时发生错误:{e}")
return all_weather_data
def save_to_db(weather_list):
"""将数据保存到 SQLite 数据库"""
if not weather_list:
print("未获取到任何有效天气数据,无需保存到数据库。")
return
print("\n正在将数据保存到数据库...")
db_path = "weather_data.db"
# 如果之前有旧数据库,先删除,确保数据不翻倍
if os.path.exists(db_path):
os.remove(db_path)
conn = sqlite3.connect(db_path)
cursor = conn.cursor()
cursor.execute("""
CREATE TABLE IF NOT EXISTS weather_forecast (
id INTEGER PRIMARY KEY AUTOINCREMENT,
city TEXT,
date TEXT,
weather TEXT,
high_temp TEXT,
low_temp TEXT,
wind_info TEXT
)
""")
cursor.executemany("""
INSERT INTO weather_forecast (city, date, weather, high_temp, low_temp, wind_info)
VALUES (?, ?, ?, ?, ?, ?)
""", [
(item["city"], item["date"], item["weather"], item["high_temp"], item["low_temp"], item["wind_info"])
for item in weather_list
])
conn.commit()
cursor.execute("SELECT * FROM weather_forecast")
rows = cursor.fetchall()
# 打印前几行数据供检查
print("\n--- 数据库数据预览 ---")
for row in rows[:5]:
print(row)
print(f"--- 共保存 {len(rows)} 条记录 ---\n")
conn.close()
print("数据库保存成功!")
if __name__ == "__main__":
all_weather = []
for city_name, city_code in CITIES.items():
data = get_weather(city_name, city_code)
all_weather.extend(data)
# 每次爬取后停顿,假装在正常浏览
time.sleep(random.uniform(1.5, 3.5))
if all_weather:
save_to_db(all_weather)
else:
print("\n未能获取到任何天气数据,请检查网络或网址是否变动。")

心得
这次作业让我对 Python 的基础语法有了更清楚的认识。刚开始写代码时,我对变量、输入输出、条件判断和循环的使用还不够熟练,经常出现缩进错误、变量名写错或者程序运行结果不符合预期的情况。后来我通过逐行检查代码,把每一步想要实现的功能写清楚,再对照报错信息修改,程序终于能够正常运行。
通过完成这个作业,我明白了编程不能只靠记忆语法,更重要的是理解程序执行的顺序。比如先获取数据,再判断条件,最后输出结果,每一步都不能乱。这次练习也让我学会了遇到报错时不要慌张,而是要根据提示找到问题所在,再一点点修改。
作业2
代码及结果
import requests
import json
import sqlite3
import os
# 这里写你要爬取的股票代码,比如茅台、平安、招行
STOCK_CODES = ["sh600519", "sz000001", "sh601318"]
# 新浪财经的股票数据接口
URL = "https://hq.sinajs.cn/list="
# 伪造一下请求头,防止被网站反爬
HEADERS = {
"Referer": "https://finance.sina.com.cn/",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36"
}
def get_stock_data(codes):
"""抓取股票的实时数据"""
stock_data = []
# 把股票代码用逗号拼起来传给接口
params_codes = ",".join(codes)
request_url = URL + params_codes
print(f"正在获取 {len(codes)} 只股票的数据...")
try:
# 发送请求,新浪返回的是GBK编码的
response = requests.get(request_url, headers=HEADERS, timeout=10)
response.encoding = "gbk"
text = response.text
lines = text.strip().split("\n")
for line in lines:
try:
# 截取双引号里面的真实数据
parts = line.split('"')
if len(parts) > 1:
var_part = parts[0]
data_part = parts[1]
code = var_part.split("_")[-1] # 拿到股票代号
data_list = data_part.split(",")
# 提取名称、当前价、涨跌额和成交量
name = data_list[0]
price = data_list[3]
change = data_list[31]
volume = data_list[8]
# 把这些数据存到字典里
stock_data.append({
"code": code,
"name": name,
"price": price,
"change": change,
"volume": volume
})
except Exception:
continue
print("数据获取成功!")
except Exception as e:
print(f"请求出错:{e}")
return stock_data
def save_to_db(data_list):
"""把数据存到本地数据库,顺便在控制台打印出来看看"""
if not data_list:
print("没有数据,先不存了。")
return
print("正在保存数据到数据库...")
db_path = "stock_data.db"
# 删掉旧的数据库,防止每次运行数据重复
if os.path.exists(db_path):
os.remove(db_path)
conn = sqlite3.connect(db_path)
cursor = conn.cursor()
# 建个表用来存股票数据
cursor.execute("""
CREATE TABLE IF NOT EXISTS stocks (
id INTEGER PRIMARY KEY AUTOINCREMENT,
code TEXT,
name TEXT,
price TEXT,
change TEXT,
volume TEXT
)
""")
# 一条一条插进去
for stock in data_list:
cursor.execute("""
INSERT INTO stocks (code, name, price, change, volume)
VALUES (?, ?, ?, ?, ?)
""", (stock["code"], stock["name"], stock["price"], stock["change"], stock["volume"]))
conn.commit()
# 打印个表格,直观地看结果
print("\n" + "=" * 70)
print(f"{'股票代码':<12} {'股票名称':<12} {'当前价格':<10} {'涨跌额':<10} {'成交量':<20}")
print("-" * 70)
for stock in data_list:
print(f"{stock['code']:<12} {stock['name']:<12} {stock['price']:<10} {stock['change']:<10} {stock['volume']:<20}")
print("=" * 70)
print(f"\n保存成功,共 {len(data_list)} 条数据!")
conn.close()
# 主程序入口,直接运行就行
if __name__ == "__main__":
data = get_stock_data(STOCK_CODES)
save_to_db(data)

心得
第二个作业比第一个稍微复杂一些,主要涉及数据整理、函数调用或列表、字典等结构的使用。刚开始我在设计程序逻辑时比较混乱,不知道应该把哪些功能放在函数里,也不知道怎样让代码更简洁。写完后运行程序,还出现过数据格式不对、结果重复或漏掉部分内容的情况。
后来我先把作业要求拆成几个小步骤,分别实现后再把它们组合起来。通过反复测试不同输入,我发现程序在边界情况下容易出错,于是又补充了一些判断条件。这个作业让我体会到,写代码之前先理清思路很重要,函数可以让程序结构更清晰,也方便后面修改和检查。
作业3
代码及结果
import requests
from bs4 import BeautifulSoup
import sqlite3
import os
# 目标网页地址
URL = "https://www.shanghairanking.cn/rankings/bcur/2021"
# 伪装成浏览器,防止被拦截
HEADERS = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36"
}
def get_rankings():
"""从网页上直接解析大学排名数据"""
print("正在解析网页数据...")
try:
# 1. 发送 GET 请求获取网页源码
resp = requests.get(URL, headers=HEADERS, timeout=10)
resp.encoding = "utf-8"
# 2. 使用 BeautifulSoup 解析网页
soup = BeautifulSoup(resp.text, 'html.parser')
# 3. 找到网页上的表格
table = soup.find('table', class_='rank-table')
if not table:
print("解析失败,网页结构可能发生了变动。")
return []
universities = []
# 4. 获取表格里除表头外的所有行
rows = table.find_all('tr')
for row in rows[1:]:
cols = row.find_all('td')
if len(cols) >= 4:
# 依次提取 排名、学校名称、所在省市、总分
rank = cols[0].text.strip()
school_name = cols[1].text.strip()
province = cols[2].text.strip()
total_score = cols[3].text.strip()
# 软科通常不直接显示类型,我们这里用学校名称的包含关系简单推断一下
school_type = "综合"
for type_keyword in ["理工", "师范", "医药", "农业", "林业", "财经", "政法", "语言", "民族", "体育", "艺术"]:
if type_keyword in school_name:
school_type = type_keyword
break
universities.append({
"rank": rank,
"school_name": school_name,
"province": province,
"school_type": school_type,
"total_score": total_score
})
print(f"成功解析到 {len(universities)} 所大学的排名数据。")
return universities
except Exception as e:
print(f"获取数据发生错误:{e}")
return []
def save_and_print(records):
"""将数据存入本地数据库,并在控制台打印前 20 条"""
if not records:
print("没有获取到数据。")
return
db_path = "rankings_2021.db"
# 删除旧数据防止重复
if os.path.exists(db_path):
os.remove(db_path)
conn = sqlite3.connect(db_path)
cursor = conn.cursor()
# 建表
cursor.execute("""
CREATE TABLE IF NOT EXISTS universities (
id INTEGER PRIMARY KEY AUTOINCREMENT,
rank TEXT,
school_name TEXT,
province TEXT,
school_type TEXT,
total_score TEXT
)
""")
# 准备插入的数据
insert_list = []
for item in records:
insert_list.append((
item['rank'],
item['school_name'],
item['province'],
item['school_type'],
item['total_score']
))
# 批量写入数据库
cursor.executemany(
"INSERT INTO universities (rank, school_name, province, school_type, total_score) VALUES (?, ?, ?, ?, ?)",
insert_list
)
conn.commit()
# 格式化打印前 20 条结果
print("\n" + "=" * 80)
print(f"{'排名':<6} {'学校名称':<25} {'省份':<10} {'类型':<15} {'总分':<10}")
print("-" * 80)
for item in insert_list[:20]:
print(f"{str(item[0]):<6} {str(item[1]):<25} {str(item[2]):<10} {str(item[3]):<15} {str(item[4]):<10}")
print("=" * 80)
print(f"已将 {len(insert_list)} 条数据成功保存到 {db_path} 中!")
conn.close()
if __name__ == "__main__":
data = get_rankings()
save_and_print(data)

心得
第三个作业综合性更强,需要把前面学到的知识结合起来完成一个相对完整的任务。刚开始我觉得任务量比较大,不知道从哪里开始,写代码时也遇到过逻辑不完整、文件读取失败、输出结果不正确等问题。尤其是一些细节处理,比如数据格式转换、循环条件设置、结果保存等,都需要考虑得比较仔细。
在完成过程中,我先分析作业要得到什么结果,再倒推需要哪些步骤,最后逐步实现。遇到错误时,我会先查看报错位置,再打印中间结果,确认数据是否符合预期。通过这个作业,我不仅提高了编程能力,也学会了如何把复杂问题拆成小问题来解决。整体来看,这次作业让我对 Python 的实际应用有了更真实的感受,也增强了独立完成编程任务的信心。
浙公网安备 33010602011771号