数据采集第二次作业
数据采集第二次作业
运行环境:Windows 11、Python 3.13
主要依赖:requests、beautifulsoup4、json(标准库)、sqlite3(标准库)
作业内容:分别完成天气预报、股票行情、大学排名三个定向爬虫,抓取数据并写入 SQLite 数据库。
一、作业实现(代码与运行结果)
1.1 中国天气网 7 日天气预报爬虫
功能说明:抓取北京、上海、福州、广州、杭州 5 个城市未来 7 天的天气预报(日期、天气现象、最高/最低气温、风向、风力),解析后批量写入 SQLite 表 weather_forecast。页面为 HTML 结构,使用 BeautifulSoup 配合 CSS 选择器解析。
核心代码(weather_spider.py):
def fetch_weather_page(city_code):
"""请求指定城市的 7 日预报页面,返回 HTML 文本。"""
url = f"http://www.weather.com.cn/weather/{city_code}.shtml"
resp = requests.get(url, headers=HEADERS, timeout=10)
resp.encoding = resp.apparent_encoding or "utf-8"
resp.raise_for_status()
return resp.text
def parse_weather(html, city, city_code):
"""解析 7 日预报页面,提取每天的天气信息。"""
soup = BeautifulSoup(html, "html.parser")
day_list = soup.select("ul.t.clearfix li")
records = []
crawl_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
for li in day_list:
# 日期:<h1>19日</h1>
date_tag = li.find("h1")
forecast_date = date_tag.get_text(strip=True) if date_tag else ""
# 天气现象:<p class="wea">多云</p>
wea_tag = li.find("p", class_="wea")
weather = wea_tag.get_text(strip=True) if wea_tag else ""
# 温度:<p class="tem"> 中 <span> 为高温,<i> 为低温;去除 ℃ 符号
temp_high, temp_low = "", ""
tem_tag = li.find("p", class_="tem")
if tem_tag:
high_tag = tem_tag.find("span")
low_tag = tem_tag.find("i")
temp_high = high_tag.get_text(strip=True).replace("℃", "") if high_tag else ""
temp_low = low_tag.get_text(strip=True).replace("℃", "") if low_tag else ""
# 风向风力:<p class="win"> 中 <span> 为风向,<i> 为风力
wind_direction, wind_power = "", ""
win_tag = li.find("p", class_="win")
if win_tag:
dir_tag = win_tag.find("span")
if dir_tag:
wind_direction = dir_tag.get("title") or dir_tag.get_text(strip=True)
power_tag = win_tag.find("i")
wind_power = power_tag.get_text(strip=True) if power_tag else ""
records.append(
{
"city": city,
"city_code": city_code,
"forecast_date": forecast_date,
"weather": weather,
"temp_high": temp_high,
"temp_low": temp_low,
"wind_direction": wind_direction,
"wind_power": wind_power,
"crawl_time": crawl_time,
}
)
return records
运行结果:5 个城市 × 7 天,共入库 35 条天气预报。


1.2 新浪股票行情爬虫
功能说明:通过浏览器 F12 调试抓包得到新浪行情列表 JSON 接口,使用 requests 分页请求、json 解析返回数据,提取股票代码、名称、最新价、涨跌幅、涨跌额、成交量、成交额,写入 SQLite 表 stock_quote。脚本含失败重试、页间休眠和单页异常隔离。
核心代码(stock_spider.py):
def fetch_stock_page(session, page):
"""请求一页股票行情数据,失败时按 RETRY_TIMES 自动重试。"""
params = {**QUERY_PARAMS, "page": page, "num": PAGE_SIZE}
last_error = None
for attempt in range(1, RETRY_TIMES + 1):
try:
resp = session.get(LIST_URL, params=params, headers=HEADERS, timeout=10)
resp.raise_for_status()
return json.loads(resp.text)
except requests.RequestException as e:
last_error = e
if attempt < RETRY_TIMES:
time.sleep(RETRY_DELAY)
raise last_error
def parse_stocks(data):
"""从接口返回的 JSON 数组中提取股票信息,映射为数据库记录。"""
crawl_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
records = []
for item in data or []:
records.append(
{
"code": item.get("code"),
"name": item.get("name"),
"price": _to_float(item.get("trade")),
"change_pct": _to_float(item.get("changepercent")),
"change_amount": _to_float(item.get("pricechange")),
"volume": _to_float(item.get("volume")),
"turnover": _to_float(item.get("amount")),
"crawl_time": crawl_time,
}
)
return records
运行结果:分页抓取 10 页,共入库 500 条股票行情。

股票爬虫运行截图
1.3 软科中国大学排名爬虫
功能说明:通过 F12 抓包得到软科排名 JSON 接口 /api/pub/v1/bcur,按 bcur_type=11(中国大学主榜)、year=2021 请求数据;解析嵌套在 data.rankings 中的院校列表,提取排名、学校名称、省市、院校类型、总分,写入 SQLite 表 university_2021。
核心代码(university_ranking_spider.py):
def parse_universities(data):
"""
从接口 JSON 中提取院校信息,映射为数据库记录。
接口字段:ranking 排名、univNameCn 学校、province 省市、
univCategory 类型、score 总分;并对旧字段名做兼容。
"""
rankings = (data.get("data") or {}).get("rankings") or []
crawl_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
records = []
for item in rankings:
records.append(
{
"rank": _to_int(item.get("ranking") or item.get("rankOverall") or item.get("rank")),
"school": item.get("univNameCn") or item.get("univ_name") or item.get("name"),
"province": item.get("province"),
"school_type": item.get("univCategory") or item.get("type"),
"score": item.get("score"),
"crawl_time": crawl_time,
}
)
return records
def save_records(conn, records):
cursor = conn.cursor()
cursor.execute("DELETE FROM university_2021")
cursor.executemany(
"""
INSERT INTO university_2021
(rank, school, province, school_type, score, crawl_time)
VALUES
(:rank, :school, :province, :school_type, :score, :crawl_time)
""",
records,
)
conn.commit()
运行结果:共入库 582 所院校(2021 软科中国大学主榜)。

大学排名爬虫运行gif
二、作业心得体会
2.1 技术要点与收获
通过本次三个爬虫作业,我完整走通了「分析目标站点 → 定位数据来源(HTML 页面或 JSON 接口)→ 发送请求 → 解析提取 → 清洗转换 → 入库保存」的爬虫流程,对网络爬虫的基本原理有了直观认识。
- 两种数据获取方式:天气网是传统的 HTML 页面,需要用
BeautifulSoup按标签和 class 选择器逐层定位;股票和大学排名则是页面通过 JS 异步加载的 JSON 接口,需要打开浏览器 F12 → Network(网络)面板,在 Fetch/XHR 中找到真正返回数据的请求,再用json模块解析。这让我明白:看到网页上的数据,先要判断它是服务端渲染在 HTML 里,还是前端通过接口异步获取的,两者解析思路完全不同。 - 请求伪装与稳定性:三个脚本都携带了
User-Agent模拟浏览器访问,股票接口还补充了Referer;同时通过超时设置、失败重试、页间休眠等方式,让程序在网络波动时更健壮,也避免请求过于频繁给服务器造成压力。 - 数据清洗与类型转换:网页/接口返回的温度、价格、成交量等多为字符串,需要统一转为数值类型;对于停牌、字段缺失等情况,用
try/except兜底返回None,避免程序中断。 - 数据库设计:使用标准库
sqlite3建表、参数化插入(executemany+ 命名占位符),既防止 SQL 注入,也提高了批量写入效率;每次入库前清空旧表,保证重复运行不会产生重复数据。
2.2 遇到的问题与解决过程
- 页面编码乱码:天气网页面编码不固定,最初直接指定
utf-8出现中文乱码,改用resp.apparent_encoding自动识别响应编码后解决。 - 接口字段名确认:大学排名接口返回的字段是
ranking、univNameCn、province、univCategory、score,与页面上显示的中文含义不能凭字面猜测;通过 F12 的 Response/Preview 对照实际 JSON,逐一确认字段后再做映射,并对可能的旧字段名做了兼容。 - 并列名次不能设唯一约束:大学排名中存在并列名次,最初在排名字段上加唯一约束导致并列记录被覆盖、入库数量减少;去掉唯一约束后,582 所院校才完整保存。
- 分页与异常隔离:股票爬虫按页码循环翻页,单页请求失败时只打印提示并继续后续页,不影响整体流程;当某一页返回空列表时结束翻页,避免无效请求。
2.3 总结与不足
这次作业让我体会到,爬虫的难点往往不在写请求,而在前期分析站点结构和后期数据清洗:能否在 F12 中准确定位数据接口、读懂返回的 JSON 层级,直接决定了解析代码怎么写。同时我也意识到自己还有不少不足:目前只处理了静态页面和公开 JSON 接口,对于需要登录、Cookie 校验、动态渲染(JS 渲染)以及反爬加密参数的站点,还缺乏经验;代码层面的日志记录、异常分类和配置抽象也有优化空间。后续我会结合 Scrapy 框架进一步学习工程化爬虫,并加强对前端网络请求、异步加载原理的理解。


浙公网安备 33010602011771号