数据采集第2次作业

数据采集第二次作业

学号:102402135

姓名:王伟浩

课程:数据采集与融合技术

作业链接:第二次作业

本次作业使用 Python 完成三个数据采集任务:从中国气象网获取 5 个城市的 7 日天气预报;使用 requests 和 JSON 解析获取股票行情;采集软科 2021 中国大学排名主榜。采集结果保存在 SQLite 数据库中。

实验环境

项目 配置
编程语言 Python 3
主要依赖 requests、beautifulsoup4
数据库 SQLite(Python 自带 sqlite3 模块)
代码仓库 Gitee 作业二文件夹,按作业分开:任务1 | 任务2 | 任务3

作业①:

要求:在中国气象网( http://www.weather.com.cn )给定城市集【3-5个城市】的7日天气预报,并保存在数据库。

一.实验

1. 代码设计思路

本程序使用 requests 请求中国天气网的城市 7 日预报页面,利用 BeautifulSoup 通过 CSS 选择器 ul.t.clearfix > li 定位 7 天的天气列表,逐天提取日期、天气现象、最高温、最低温、风向和风力,再根据采集日期推算标准日期,最后把 5 个城市共 35 条记录写入 SQLite 数据库 weather.db。

2. 可能遇到的问题

页面上的日期是“15日(今天)”这类相对文本,没有年月,跨月跨年就无法区分,需要按采集日期和列表序号换算成标准日期;“今天”这一条只有夜间温度(<i> 标签),没有最高温对应的 <span>,需要和其余 6 天分开处理,不能把单个温度当成最高温;数据库如果直接追加写入,重复运行会不断累积重复记录,需要为(城市、日期)建立唯一约束并覆盖写入。

3. 关键代码分析

CITIES = {
    "北京": "101010100",
    "上海": "101020100",
    "广州": "101280101",
    "深圳": "101280601",
    "杭州": "101210101",
}

LIST_URL = "https://www.weather.com.cn/weather/{code}.shtml"

(1)配置城市与地址模板: 中国天气网的城市页地址由 9 位城市编码决定,程序把 5 个城市的名称和编码放在字典中维护,再用字符串模板拼接出具体请求地址。

response = requests.get(url, headers=HEADERS, timeout=REQUEST_TIMEOUT)
response.raise_for_status()
response.encoding = "utf-8"

(2)发送请求并设置编码: 使用 requests.get() 发送 GET 请求,请求头中带 User-Agent 和 Referer,模拟浏览器访问;站点本身使用 UTF-8,直接指定编码,避免自动识别出现乱码。

soup = BeautifulSoup(html, "html.parser")
day_items = soup.select("ul.t.clearfix > li")

(3)解析并定位天气列表: 使用 BeautifulSoup 解析页面,通过 CSS 选择器定位 7 天预报的列表,其中每个 <li> 对应一天,取前 7 个即可。

high_node = temperature_node.select_one("span")
low_node = temperature_node.select_one("i")

temp_high = to_int_temperature(high_node.get_text(strip=True) if high_node else "")
temp_low = to_int_temperature(low_node.get_text(strip=True) if low_node else "")

(4)解析最高温与最低温: 页面中 <span> 是最高温、<i> 是最低温,“今天”那一条没有 <span>,因此最高温为空、最低温保留,并用正则把“8℃”这样的文本转成整数。

forecast_date = today + timedelta(days=index)

(5)推算标准日期: 以采集当天日期加上列表序号得到 YYYY-MM-DD,同时把页面原文(如“15日(今天)”)另存一列,既能计算也能核对。

UNIQUE (city_code, forecast_date)

INSERT OR REPLACE INTO weather_forecast (
    city, city_code, forecast_date, ...

(6)建表与写库: 为(城市编码、预报日期)建立唯一约束,配合 INSERT OR REPLACE 覆盖写入,重复运行不会产生重复记录。

完整代码:

# -*- coding: utf-8 -*-
"""
作业①:爬取中国气象网( http://www.weather.com.cn )5 个城市的 7 日天气预报,并保存到 SQLite 数据库。

实现思路
1. 中国气象网的 7 日预报页地址规则为 https://www.weather.com.cn/weather/{城市编码}.shtml,
城市编码(9 位)在 CITIES 字典中维护。
2. 用 requests 发起 GET 请求,BeautifulSoup 解析页面中的 <ul class="t clearfix"> 列表,
该列表下的每个 <li> 就是一天,共 7 天。
3. 逐天解析:日期、天气现象、最高温、最低温、风向、风力,再按抓取日期推算标准日期
(YYYY-MM-DD),最后写入 SQLite 的 weather_forecast 表。

运行方式
python weather.py
数据库文件 weather.db 会生成在本脚本所在目录(与运行目录无关)。

数据结构说明(易错点)
页面上“今天”那一天只有夜间温度(<p class="tem"><i>4℃</i></p>,没有 <span>),
所以今天的最高温为 NULL;<span> 对应最高温、<i> 对应最低温,这是页面的固定结构。
"""

import os
import re
import sqlite3
import time
import unicodedata
from datetime import datetime, timedelta

import requests
from bs4 import BeautifulSoup

==================== 基础配置 ====================

数据库放在脚本所在目录,保证从任何路径运行都能把库写回本文件夹

BASE_DIR = os.path.dirname(os.path.abspath(file))
DB_PATH = os.path.join(BASE_DIR, "weather.db")

城市名 -> 中国气象网城市编码(作业要求 3~5 个城市,这里取 5 个)

CITIES = {
"北京": "101010100",
"上海": "101020100",
"广州": "101280101",
"深圳": "101280601",
"杭州": "101210101",
}

7 日天气预报页面地址模板

LIST_URL = "https://www.weather.com.cn/weather/{code}.shtml"

请求头:带上 UA 与 Referer,避免被识别为爬虫

HEADERS = {
"User-Agent": (
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
"AppleWebKit/537.36 (KHTML, like Gecko) "
"Chrome/130.0.0.0 Safari/537.36"
),
"Referer": "https://www.weather.com.cn/",
}

REQUEST_RETRY = 3 # 每个城市最多请求次数
REQUEST_TIMEOUT = 15 # 单次请求超时时间(秒)
REQUEST_INTERVAL = 1.0 # 城市之间的间隔秒数,降低被封 IP 的概率
FORECAST_DAYS = 7 # 只取未来 7 天

WEEKDAYS = ("周一", "周二", "周三", "周四", "周五", "周六", "周日")

==================== 终端表格对齐工具 ====================

def display_width(text):
"""计算字符串在终端里的显示宽度:中日韩全角字符占 2 格,其它占 1 格。"""
width = 0
for char in str(text):
width += 2 if unicodedata.east_asian_width(char) in ("W", "F") else 1
return width

def pad(text, width, align="<"):
"""按显示宽度补齐空格,保证中文表格不会错列。align 取 '<' 左对齐、'>' 右对齐。"""
text = "" if text is None else str(text)
blank = " " * max(width - display_width(text), 0)
return blank + text if align == ">" else text + blank

def format_row(cells):
"""把若干 (内容, 宽度, 对齐) 单元格拼成一行,列与列之间留一个空格。"""
return " ".join(pad(text, width, align) for text, width, align in cells)

==================== 数据抓取与解析 ====================

def fetch_html(city, city_code):
"""请求某个城市的 7 日预报页面,失败时重试,全部失败返回 None。"""
url = LIST_URL.format(code=city_code)

for attempt in range(1, REQUEST_RETRY + 1):
try:
response = requests.get(url, headers=HEADERS, timeout=REQUEST_TIMEOUT)
response.raise_for_status()
# 站点本身是 UTF-8,直接指定编码,避免 apparent_encoding 猜错出现乱码
response.encoding = "utf-8"
return response.text
except requests.RequestException as error:
print(f" {city} 第 {attempt} 次请求失败:{error}")
if attempt < REQUEST_RETRY:
time.sleep(attempt * 1.5) # 退避等待后再试

return None

def to_int_temperature(text):
"""把 '8℃'、'-3℃' 之类的文本转成整数温度,取不到数字返回 None。"""
if not text:
return None
match = re.search(r"-?\d+", text)
return int(match.group()) if match else None

def parse_temperature(item):
"""
解析一天的温度。

页面结构:<p class="tem"><span>8℃</span>/<i>2℃</i></p>
span 是最高温、i 是最低温;“今天”一条只有 i(夜间温度),此时最高温为 None。
返回 (最高温, 最低温, 原始文本)。
"""
temperature_node = item.select_one("p.tem")
if temperature_node is None:
return None, None, ""

high_node = temperature_node.select_one("span")
low_node = temperature_node.select_one("i")

temp_high = to_int_temperature(high_node.get_text(strip=True) if high_node else "")
temp_low = to_int_temperature(low_node.get_text(strip=True) if low_node else "")
temp_text = temperature_node.get_text("", strip=True)

return temp_high, temp_low, temp_text

def parse_wind(item):
"""解析风向与风力,风向取 span 的 title 属性;白天、夜间相同则只保留一个。"""
directions = []
for node in item.select("p.win em span"):
direction = node.get("title") or node.get_text(strip=True)
if direction and direction not in directions:
directions.append(direction)

levels = []
for node in item.select("p.win i"):
level = node.get_text(strip=True)
if level and level not in levels:
levels.append(level)

return "、".join(directions), "、".join(levels)

def parse_forecast(city, city_code, html, crawl_time):
"""解析整页 7 天预报,返回记录列表。"""
soup = BeautifulSoup(html, "html.parser")
day_items = soup.select("ul.t.clearfix > li")

if not day_items:
return []

页面上的日期是“15日(今天)”这种相对描述,用抓取日期 + 序号推算标准日期

today = datetime.strptime(crawl_time, "%Y-%m-%d %H:%M:%S").date()
records = []

for index, item in enumerate(day_items[:FORECAST_DAYS]):
date_text = item.select_one("h1").get_text(strip=True) if item.select_one("h1") else ""
weather_node = item.select_one("p.wea")
if weather_node is None:
weather = ""
else:
# title 属性是完整天气现象(如“阴转多云”),比纯文本更可靠
weather = weather_node.get("title") or weather_node.get_text(strip=True)

temp_high, temp_low, temp_text = parse_temperature(item)
wind_direction, wind_level = parse_wind(item)

forecast_date = today + timedelta(days=index)

第 0 条是“今天”,第 1 条是“明天”,用序号推算星期比解析文本更稳

records.append({
"city": city,
"city_code": city_code,
"forecast_date": forecast_date.isoformat(),
"date_text": date_text,
"weekday": WEEKDAYS[forecast_date.weekday()],
"weather": weather,
"temp_high": temp_high,
"temp_low": temp_low,
"temp_text": temp_text,
"wind_direction": wind_direction,
"wind_level": wind_level,
"crawl_time": crawl_time,
})

return records

==================== 数据库操作 ====================

def create_table(connection):
"""创建天气预报表;(city_code, forecast_date) 唯一,保证同一天只保留最新一次采集结果。"""
connection.execute("""
CREATE TABLE IF NOT EXISTS weather_forecast (
id INTEGER PRIMARY KEY AUTOINCREMENT,
city TEXT NOT NULL,
city_code TEXT NOT NULL,
forecast_date TEXT NOT NULL,
date_text TEXT,
weekday TEXT,
weather TEXT,
temp_high INTEGER,
temp_low INTEGER,
temp_text TEXT,
wind_direction TEXT,
wind_level TEXT,
crawl_time TEXT NOT NULL,
UNIQUE (city_code, forecast_date)
)
""")
connection.commit()

def save_records(connection, records):
"""批量写入数据库,主键冲突时覆盖旧记录,避免每跑一次就多出一批重复数据。"""
connection.executemany("""
INSERT OR REPLACE INTO weather_forecast (
city, city_code, forecast_date, date_text, weekday, weather,
temp_high, temp_low, temp_text, wind_direction, wind_level, crawl_time
) VALUES (
:city, :city_code, :forecast_date, :date_text, :weekday, :weather,
:temp_high, :temp_low, :temp_text, :wind_direction, :wind_level, :crawl_time
)
""", records)
connection.commit()

def show_database(connection):
"""从数据库查出全部记录并打印,用于检查结果(终端表格按中文宽度对齐)。"""
rows = connection.execute("""
SELECT city, forecast_date, weekday, weather,
temp_high, temp_low, wind_direction, wind_level
FROM weather_forecast
ORDER BY city_code, forecast_date
""").fetchall()

列定义:(表头, 宽度, 对齐),行与表头共用,保证对齐一致

columns = [
("城市", 8, "<"), ("日期", 12, "<"), ("星期", 6, "<"), ("天气", 16, "<"),
("最高温", 8, ">"), ("最低温", 8, ">"), ("风向", 18, "<"), ("风力", 12, "<"),
]
line = "=" * (sum(width for _, width, _ in columns) + len(columns) - 1)

print("\n" + line)
print("数据库 weather_forecast 表内容(按城市、日期排序)")
print(line)
print(format_row([(title, width, align) for title, width, align in columns]))
print("-" * len(line))

for row in rows:
city, forecast_date, weekday, weather, temp_high, temp_low, wind_direction, wind_level = row
print(format_row([
(city, 8, "<"),
(forecast_date, 12, "<"),
(weekday, 6, "<"),
(weather, 16, "<"),
("" if temp_high is None else f"{temp_high}℃", 8, ">"),
("" if temp_low is None else f"{temp_low}℃", 8, ">"),
(wind_direction, 18, "<"),
(wind_level, 12, "<"),
]))

print("-" * len(line))

total = connection.execute("SELECT COUNT(*) FROM weather_forecast").fetchone()[0]
cities = connection.execute(
"SELECT COUNT(DISTINCT city) FROM weather_forecast"
).fetchone()[0]
latest = connection.execute(
"SELECT MAX(crawl_time) FROM weather_forecast"
).fetchone()[0]

print(f"库内记录总数:{total} 条 城市数:{cities} 个 最近采集时间:{latest}")

==================== 主流程 ====================

def main():
"""程序入口:逐个城市抓取 -> 解析 -> 汇总 -> 写库 -> 展示。"""
crawl_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")

print("=" * 96)
print("作业① 中国气象网 7 日天气预报爬取")
print(f"目标城市:{'、'.join(CITIES.keys())}")
print(f"采集时间:{crawl_time}")
print("=" * 96)

connection = sqlite3.connect(DB_PATH)
create_table(connection)

all_records = []

for city, city_code in CITIES.items():
print(f"\n[抓取] {city}(编码 {city_code})")
html = fetch_html(city, city_code)

if not html:
print(f" {city} 请求失败,跳过该城市。")
continue

records = parse_forecast(city, city_code, html, crawl_time)
if not records:
print(f" {city} 页面解析不到数据,页面结构可能已改版。")
continue

print(f" 解析成功,共 {len(records)} 天:")
for record in records:
high = "-" if record["temp_high"] is None else f"{record['temp_high']}℃"
low = "-" if record["temp_low"] is None else f"{record['temp_low']}℃"
print(
f" {record['forecast_date']} {record['weekday']} "
f"{pad(record['weather'], 14)}"
f"{pad(high, 7, '>')}/{pad(low, 7)} "
f"{record['wind_direction']} {record['wind_level']}"
)

all_records.extend(records)
time.sleep(REQUEST_INTERVAL) # 城市之间暂停,礼貌抓取

if not all_records:
print("\n本次没有采集到任何数据,数据库未做修改。")
connection.close()
return

save_records(connection, all_records)
print(f"\n[写库] 本次写入 {len(all_records)} 条记录 -> {DB_PATH}")

show_database(connection)
connection.close()

if name == "main":
main()

### **运行结果:**

终端输出 5 个城市、每个城市 7 天的天气,写入数据库后再从库中读回打印校验:

天气爬虫运行结果:

aeafc5499ce7af685f7044decafab49c (1)

数据库中 weather_forecast 表的内容,由 DB Browser for SQLite 打开:

天气数据表:

b16a0e4cb7fd58dee9a3437e144be1c0
全部数据见gitee的csv文件

二.心得体会

通过本次实验,我熟悉了使用 requests 请求网页以及使用 BeautifulSoup 解析网页的基本方法。通过实际爬取中国天气网的 7 日天气预报,我了解到网页中的日期可能只是“今天”“明天”这样的相对文本,入库时需要改写成标准日期;同时也认识到数据库表需要设置合适的唯一约束,否则重复运行会造成数据重复。最终程序能够把 5 个城市的 7 日天气全部写入数据库并读回校验,加深了我对网页数据采集与存储流程的理解。

作业②、③:

要求②:用 requests 和 json 解析方法定向爬取股票相关信息,并存储在数据库中。候选网站:东方财富网 https://www.eastmoney.com/ 、新浪股票 http://finance.sina.com.cn/stock/ 。

要求③:爬取中国大学 2021 主榜( https://www.shanghairanking.cn/rankings/bcur/2021 )所有院校信息,并存储在数据库中,同时将浏览器 F12 调试分析的过程录制 Gif 加入至博客中。

一.实验

1. 代码设计思路

这两个题目页面上都看不到数据,排行榜和股票列表都是前端用 JavaScript 请求接口后渲染出来的,因此程序改用 requests 请求浏览器实际调用的 JSON 接口,用 response.json() 解析返回结果。

作业②使用东方财富的行情列表接口 https://push2.eastmoney.com/api/qt/clist/get,通过 pn(页码)、pz(每页条数)、fid(排序字段)、fs(市场范围)和 fields(字段列表)参数控制返回内容,按股票代码升序抓取前 10 页共 1000 只股票,解析后写入 SQLite 数据库 stock.db。

作业③使用软科排名的数据接口 https://www.shanghairanking.cn/api/pub/v1/bcur,参数 bcur_type=11 表示主榜、year=2021 表示 2021 年,接口一次返回全部 582 所院校,解析后写入 SQLite 数据库 university.db。

2. 可能遇到的问题

东方财富的接口有访问频率限制,短时间内连续请求会出现连接被断开(RemoteDisconnected)的情况,因此每页都做了重试和退避,并且在整体不可用时自动切换到新浪财经的行情接口;两个数据源的字段含义不完全一致,成交量单位(股与手)、总市值单位(万元与元)需要换算统一。股票接口返回的大量字段中有用字段要通过 fields 参数指定,数值中的“-”表示停牌或无数据,需要在转换时判空处理。软科接口必须带正确的 Referer,否则可能返回 403;排行榜页面如果不抓接口,HTML 中取不到任何院校数据。两题都存在重复采集的问题,需要分别用主键和唯一约束配合覆盖写入或更新写入。

3. 关键代码分析

(一)作业②:东方财富股票信息

params = {
    "pn": page,          # 页码
    "pz": PAGE_SIZE,     # 每页条数
    "po": 0,             # 0 升序,1 降序
    "fid": "f12",        # 按股票代码排序
    "fs": MARKET_FILTER, # 沪深 A 股范围
    "fields": FIELDS,    # 需要返回的字段
}

(1)设置请求参数: 通过 pn 控制页码、pz 控制每页条数、fid 指定排序字段(f12 为股票代码)、fs 指定市场范围,fields 指定需要返回的字段,返回内容随之变化,可以减少无关数据。

FIELDS = "f12,f14,f2,f3,f4,f5,f6,f7,f8,f9,f15,f16,f17,f18,f20"

(2)按字段编码取数: 接口用 f 编码表示字段,f12 为代码、f14 为名称、f2 为最新价、f3 为涨跌幅、f4 为涨跌额、f5 为成交量、f6 为成交额、f7 为振幅、f8 为换手率、f9 为市盈率、f20 为总市值,程序只请求需要的 15 个字段。

response = requests.get(url, params=params, headers=headers, timeout=REQUEST_TIMEOUT)
response.raise_for_status()
return response.json()

(3)请求并解析 JSON: 使用 requests.get() 携带参数发送请求,再用 response.json() 把返回内容解析成字典,避免手工解析字符串。

data = result.get("data")
diff = data.get("diff") or []
if isinstance(diff, dict):
    diff = list(diff.values())
total_count = data.get("total")

(4)提取股票列表: 接口返回结果中 data.total 是市场总只数,data.diff 是股票数组;个别参数组合下 diff 是字典,程序统一转成列表后遍历。

stock = {
    "code": str(item.get("f12", "")).strip(),
    "name": str(item.get("f14", "")).strip(),
    "price": to_number(item.get("f2")),
    "change_percent": to_number(item.get("f3")),
    ...
}

(5)映射字段: 按 f 编码把每条 JSON 转换成数据库字段,数值统一用 to_number() 处理,“-”、空串和 None 都转成 None,避免写入时报错。

with connection:                       # 正常结束提交,异常回滚
    connection.execute("DELETE FROM stocks")
    connection.executemany("INSERT INTO stocks (...) VALUES (...)", values)

(6)事务化写库: 先把 10 页全部抓完,再在同一个事务里先清空旧快照、再批量插入;中途失败会整体回滚,不会出现清空后没写入的空库。

try:
    return collect_from_eastmoney()
except RuntimeError:
    print("[切换] 自动改用新浪财经行情接口……")
return collect_from_sina()

(7)备用数据源: 东方财富整体不可用时(返回连接被断开),程序自动改用新浪财经的行情接口继续采集,两个源的字段在解析时统一成同一套口径,数据库表结构不变。

(二)作业③:软科中国大学排名

API_URL = "https://www.shanghairanking.cn/api/pub/v1/bcur"
PARAMS = {"bcur_type": 11, "year": 2021}

HEADERS = {
    "User-Agent": "...",
    "Referer": "https://www.shanghairanking.cn/rankings/bcur/2021",
}

(1)设置接口与参数: bcur_type=11 表示主榜,year 表示年份;Referer 必须指向排名页面,否则接口可能返回 403。

response = requests.get(API_URL, params=PARAMS, headers=HEADERS, timeout=REQUEST_TIMEOUT)
rankings = response.json().get("data", {}).get("rankings") or []

(2)请求并解析排名数据: 接口一次返回当年主榜的全部院校,data.rankings 即为院校数组,不需要翻页。

records.append({
    "rank": to_int_rank(item.get("rankOverall")),
    "name": item.get("univNameCn"),
    "english_name": item.get("univNameEn"),
    "province": item.get("province"),
    "school_type": item.get("univCategory"),
    "score": to_float_score(item.get("score")),
    ...
})

(3)映射字段: rankOverall 对应排名、univNameCn 对应学校、province 对应省市、univCategory 对应类型、score 对应总分,排名和总分分别转成整数和浮点数。

UNIQUE (year, name)

ON CONFLICT(year, name) DO UPDATE SET
    rank = excluded.rank,
    score = excluded.score,
    ...

(4)写库方式: 以(年份、校名)作为唯一约束,重复采集时更新排名和分数,主键 id 保持不变,不会产生重复行。

SELECT rank, name, province, school_type, score
FROM universities WHERE year = ? ORDER BY rank ASC

(5)按五列输出: 按作业要求的“排名、学校、省市、类型、总分”五列查询并打印,并按 east_asian_width 计算显示宽度,保证中英文混排时表格对齐。

完整代码:

作业② stock.py

# -*- coding: utf-8 -*-
"""
作业②:用 requests + json 解析,定向爬取股票列表信息,并保存到 SQLite 数据库。

抓包分析(F12 -> Network -> XHR)
东方财富网的行情列表并不写在 HTML 里,而是由前端请求下面这个 JSON 接口得到:
https://push2.eastmoney.com/api/qt/clist/get
关键参数:
pn 页码
pz 每页条数
po 排序方向(1 表示降序)
fid 排序字段,f3 表示按涨跌幅排序
fs 市场筛选条件,m:0 表示深市、m:1 表示沪市,t:6/t:13/t:80 等表示板块
fields 需要返回的字段:f12 代码、f14 名称、f2 最新价、f3 涨跌幅、f4 涨跌额、
f5 成交量、f6 成交额、f7 振幅、f8 换手率、f9 市盈率、f15 最高、
f16 最低、f17 开盘、f18 昨收、f20 总市值
返回结构:{"rc":0,"data":{"total":5789,"diff":[{...}, {...}]}},data.diff 即股票列表。

运行方式
python stock.py
数据库文件 stock.db 会生成在本脚本所在目录(与运行目录无关)。

两点工程处理
1. 东方财富接口有反爬限制,短时间大量请求会被临时拒绝(RemoteDisconnected)。
因此每页都做了重试 + 退避,并且只有全部页面抓完才在同一个事务里替换数据库,
抓取失败绝不会清空已有数据。
2. 如果东方财富整体不可用(IP 被临时限制),程序会自动切换到新浪财经的行情接口
( https://vip.stock.finance.sina.com.cn/quotes_service/api/json_v2.php/... ),
两个源解析后统一成同一套字段写库,表结构不变。新浪接口同样返回 JSON,
所以本程序始终是“requests 请求 + json 解析”的实现方式。
"""

import os
import sqlite3
import time
import unicodedata

import requests

==================== 基础配置 ====================

BASE_DIR = os.path.dirname(os.path.abspath(file))
DB_PATH = os.path.join(BASE_DIR, "stock.db")

数据源 1:东方财富行情列表 JSON 接口(作业推荐的抓包目标)

EASTMONEY_URL = "https://push2.eastmoney.com/api/qt/clist/get"

数据源 2:新浪财经行情列表 JSON 接口(东方财富不可用时的备份)

SINA_URL = (
"https://vip.stock.finance.sina.com.cn"
"/quotes_service/api/json_v2.php/Market_Center.getHQNodeData"
)

请求头:带 UA 与 Referer,避免被识别为爬虫

HEADERS = {
"User-Agent": (
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
"AppleWebKit/537.36 (KHTML, like Gecko) "
"Chrome/130.0.0.0 Safari/537.36"
),
}

东方财富需要抓取的字段(f 编码含义见模块说明)

FIELDS = "f12,f14,f2,f3,f4,f5,f6,f7,f8,f9,f15,f16,f17,f18,f20"

市场范围:深市主板/创业板/中小板 + 沪市主板/科创板(A 股全市场)

MARKET_FILTER = "m:0+t:6,m:0+t:13,m:0+t:80,m:1+t:2,m:1+t:23"

PAGE_SIZE = 100 # 每页条数
MAX_PAGES = 10 # 最多抓取的页数,默认 10 页 ≈ 1000 只股票;设为 None 表示抓全市场
# 两个数据源都按股票代码升序取前 MAX_PAGES 页,口径一致
REQUEST_RETRY = 3 # 单页最多重试次数
REQUEST_TIMEOUT = 20 # 单次请求超时时间(秒)
REQUEST_INTERVAL = 0.8 # 翻页间隔秒数,降低触发限流的概率

==================== 终端表格对齐工具 ====================

def display_width(text):
"""计算字符串在终端里的显示宽度:中日韩全角字符占 2 格,其它占 1 格。"""
width = 0
for char in str(text):
width += 2 if unicodedata.east_asian_width(char) in ("W", "F") else 1
return width

def pad(text, width, align="<"):
"""按显示宽度补齐空格,保证中文表格不会错列。align 取 '<' 左对齐、'>' 右对齐。"""
text = "" if text is None else str(text)
blank = " " * max(width - display_width(text), 0)
return blank + text if align == ">" else text + blank

def format_row(cells):
"""把若干 (内容, 宽度, 对齐) 单元格拼成一行,列与列之间留一个空格。"""
return " ".join(pad(text, width, align) for text, width, align in cells)

==================== 通用工具 ====================

def to_number(value):
"""把接口返回的数值转成 float;'-'、None、空串等无效值统一返回 None。"""
if value is None or value in ("", "-"):
return None
try:
return float(value)
except (TypeError, ValueError):
return None

def request_json(url, params, referer):
"""
发送 GET 请求并解析 JSON,失败时重试 REQUEST_RETRY 次。

referer 单独传入,因为东方财富与新浪要求不同的来源页。
"""
headers = dict(HEADERS, Referer=referer)
last_error = None

for attempt in range(1, REQUEST_RETRY + 1):
try:
response = requests.get(
url, params=params, headers=headers, timeout=REQUEST_TIMEOUT
)
response.raise_for_status()
return response.json()
except (requests.RequestException, ValueError) as error:
last_error = error
print(f" 第 {attempt} 次请求失败:{error}")
if attempt < REQUEST_RETRY:
time.sleep(attempt * 1.5) # 退避等待后再试

raise RuntimeError(f"重试 {REQUEST_RETRY} 次后仍然失败:{last_error}")

==================== 数据源一:东方财富 ====================

def parse_eastmoney_item(item):
"""把东方财富接口返回的单条 JSON 转成统一字段。"""
return {
"code": str(item.get("f12", "")).strip(),
"name": str(item.get("f14", "")).strip(),
"price": to_number(item.get("f2")),
"change_percent": to_number(item.get("f3")),
"change_amount": to_number(item.get("f4")),
"volume": to_number(item.get("f5")), # 单位:手
"turnover": to_number(item.get("f6")), # 单位:元
"amplitude": to_number(item.get("f7")),
"turnover_rate": to_number(item.get("f8")),
"pe_ratio": to_number(item.get("f9")),
"high": to_number(item.get("f15")),
"low": to_number(item.get("f16")),
"open": to_number(item.get("f17")),
"prev_close": to_number(item.get("f18")),
"market_cap": to_number(item.get("f20")), # 单位:元
}

def collect_from_eastmoney():
"""按页采集东方财富数据,返回(股票列表, 页数, 市场总只数, 数据源名称)。"""
stocks = []
seen_codes = set()
total_count = None
page = 1

while True:
if MAX_PAGES is not None and page > MAX_PAGES:
break
if total_count is not None and len(stocks) >= total_count:
break

params = {
"pn": page,
"pz": PAGE_SIZE,
"po": 0, # 0 = 升序,1 = 降序
"np": 1,
"fltt": 2, # 价格、涨跌幅格式化为浮点数
"invt": 2,
"fid": "f12", # 按股票代码 f12 升序,与新浪源口径保持一致
"fs": MARKET_FILTER,
"fields": FIELDS,
}

result = request_json(EASTMONEY_URL, params, "https://quote.eastmoney.com/")
data = result.get("data")
if not data:
raise RuntimeError(f"接口未返回 data 节点:{str(result)[:150]}")

个别参数组合下 diff 是 {"0": {...}} 形式的字典,这里统一成列表

diff = data.get("diff") or []
if isinstance(diff, dict):
diff = list(diff.values())
total_count = data.get("total")

if not diff:
print(f" 第 {page} 页没有数据,采集结束。")
break

for item in diff:
stock = parse_eastmoney_item(item)
if not stock["code"] or stock["code"] in seen_codes:
continue # 跳过无代码或重复的股票
seen_codes.add(stock["code"])
stocks.append(stock)

print(f" 第 {page} 页:{len(diff)} 条(累计去重后 {len(stocks)} 条)")
page += 1
time.sleep(REQUEST_INTERVAL)

return stocks, page - 1, total_count, "东方财富"

==================== 数据源二:新浪财经(备用) ====================

def parse_sina_item(item):
"""
把新浪接口返回的单条 JSON 转成统一字段。

新浪与东方财富的口径差异在这里统一掉:
成交量 volume 单位是“股”,除以 100 换算成“手”;
总市值 mktcap 单位是“万元”,乘以 10000 换算成“元”;
接口不直接给振幅,用 (最高 - 最低) / 昨收 计算。
"""
price = to_number(item.get("trade"))
prev_close = to_number(item.get("settlement"))
high = to_number(item.get("high"))
low = to_number(item.get("low"))
volume_share = to_number(item.get("volume"))
market_cap_wan = to_number(item.get("mktcap"))

amplitude = None
if high is not None and low is not None and prev_close:
amplitude = round((high - low) / prev_close * 100, 2)

return {
"code": str(item.get("code", "")).strip(),
"name": str(item.get("name", "")).strip(),
"price": price,
"change_percent": to_number(item.get("changepercent")),
"change_amount": to_number(item.get("pricechange")),
"volume": volume_share / 100 if volume_share is not None else None,
"turnover": to_number(item.get("amount")),
"amplitude": amplitude,
"turnover_rate": to_number(item.get("turnoverratio")),
"pe_ratio": to_number(item.get("per")),
"high": high,
"low": low,
"open": to_number(item.get("open")),
"prev_close": prev_close,
"market_cap": market_cap_wan * 10000 if market_cap_wan is not None else None,
}

def collect_from_sina():
"""按页采集新浪财经数据,返回(股票列表, 页数, None, 数据源名称)。"""
stocks = []
seen_codes = set()
page = 1

while True:
if MAX_PAGES is not None and page > MAX_PAGES:
break

params = {
"page": page,
"num": PAGE_SIZE,
"sort": "code", # 按股票代码升序,与东方财富源口径保持一致
"asc": 1,
"node": "hs_a", # 沪深 A 股(含北交所)
"symbol": "",
"_s_r_a": "page",
}

rows = request_json(SINA_URL, params, "https://finance.sina.com.cn/")
if not rows:
print(f" 第 {page} 页没有数据,采集结束。")
break

for item in rows:
stock = parse_sina_item(item)
if not stock["code"] or stock["code"] in seen_codes:
continue
seen_codes.add(stock["code"])
stocks.append(stock)

print(f" 第 {page} 页:{len(rows)} 条(累计去重后 {len(stocks)} 条)")
page += 1
time.sleep(REQUEST_INTERVAL)

return stocks, page - 1, None, "新浪财经"

==================== 采集调度 ====================

def collect_stocks():
"""
采集入口:优先用东方财富,整体不可用时自动切换到新浪财经。

返回(股票列表, 页数, 市场总只数, 数据源名称)。
"""
print("[数据源] 东方财富 push2 行情接口")
try:
return collect_from_eastmoney()
except RuntimeError as error:
print(f"\n东方财富接口不可用:{error}")
print("[切换] 自动改用新浪财经行情接口……\n")

return collect_from_sina()

==================== 数据库操作 ====================

def create_table(connection):
"""创建股票表,以股票代码 code 为主键。"""
connection.execute("""
CREATE TABLE IF NOT EXISTS stocks (
code TEXT PRIMARY KEY,
name TEXT NOT NULL,
price REAL,
change_percent REAL,
change_amount REAL,
volume REAL,
turnover REAL,
amplitude REAL,
turnover_rate REAL,
pe_ratio REAL,
high REAL,
low REAL,
open REAL,
prev_close REAL,
market_cap REAL,
source TEXT,
snapshot_time TEXT NOT NULL
)
""")
connection.commit()

def save_stocks(connection, stocks, source, snapshot_time):
"""
用一个事务完成“清空旧快照 + 写入新快照”。

先 DELETE 再批量 INSERT,中途出错会整事务回滚,不会出现只清空没写入的空库。
"""
with connection: # with 块正常结束自动 commit,异常自动 rollback
connection.execute("DELETE FROM stocks")
connection.executemany("""
INSERT INTO stocks (
code, name, price, change_percent, change_amount, volume, turnover,
amplitude, turnover_rate, pe_ratio, high, low, open, prev_close,
market_cap, source, snapshot_time
) VALUES (
:code, :name, :price, :change_percent, :change_amount, :volume, :turnover,
:amplitude, :turnover_rate, :pe_ratio, :high, :low, :open, :prev_close,
:market_cap, :source, :snapshot_time
)
""", [dict(stock, source=source, snapshot_time=snapshot_time) for stock in stocks])

def show_database(connection):
"""查询数据库并打印涨幅前 20 名,用于检查采集结果。"""
# 列定义:(表头, 宽度, 对齐),行与表头共用,保证对齐一致
columns = [
("排名", 5, ">"), ("代码", 8, "<"), ("名称", 14, "<"), ("最新价", 8, ">"),
("涨跌幅", 9, ">"), ("成交额(亿)", 12, ">"), ("换手率", 8, ">"), ("振幅", 8, ">"),
]
line = "=" * (sum(width for _, width, _ in columns) + len(columns) - 1)

rows = connection.execute("""
SELECT code, name, price, change_percent, turnover, turnover_rate, amplitude
FROM stocks
ORDER BY change_percent DESC
LIMIT 20
""").fetchall()

print("\n" + "=" * len(line))
print("数据库 stocks 表 —— 涨幅前 20 名")
print("=" * len(line))
print(format_row([(title, width, align) for title, width, align in columns]))
print("-" * len(line))

for index, row in enumerate(rows, start=1):
code, name, price, change_percent, turnover, turnover_rate, amplitude = row
print(format_row([
(index, 5, ">"),
(code, 8, "<"),
(name, 14, "<"),
(f"{price:.2f}" if price is not None else "-", 8, ">"),
(f"{change_percent:.2f}%" if change_percent is not None else "-", 9, ">"),
(f"{turnover / 1e8:.2f}" if turnover is not None else "-", 12, ">"),
(f"{turnover_rate:.2f}%" if turnover_rate is not None else "-", 8, ">"),
(f"{amplitude:.2f}%" if amplitude is not None else "-", 8, ">"),
]))

print("-" * len(line))

total = connection.execute("SELECT COUNT() FROM stocks").fetchone()[0]
rise = connection.execute(
"SELECT COUNT(
) FROM stocks WHERE change_percent > 0"
).fetchone()[0]
fall = connection.execute(
"SELECT COUNT(*) FROM stocks WHERE change_percent < 0"
).fetchone()[0]
source = connection.execute("SELECT MAX(source) FROM stocks").fetchone()[0]
snapshot_time = connection.execute(
"SELECT MAX(snapshot_time) FROM stocks"
).fetchone()[0]

print(f"库内股票总数:{total} 只 上涨:{rise} 只 下跌:{fall} 只")
print(f"数据来源:{source} 快照时间:{snapshot_time}")

==================== 主流程 ====================

def main():
"""程序入口:采集 -> 校验 -> 写库 -> 展示。"""
print("=" * 92)
print("作业② 股票信息定向爬取(requests + json 解析)")
print(f"主接口:{EASTMONEY_URL}")
print(f"备用接口:{SINA_URL}")
print(f"抓取字段:{FIELDS}")
print("=" * 92)

connection = sqlite3.connect(DB_PATH)
create_table(connection)

try:
stocks, pages, total_count, source = collect_stocks()
except RuntimeError as error:
print(f"\n采集失败:{error}")
print("数据库保持原样,未被清空。")
connection.close()
return

total_text = f"接口报告全市场共 {total_count} 只" if total_count else "接口未给出总只数"
print(f"\n[采集结果] 来源:{source},共 {pages} 页,去重后 {len(stocks)} 只股票({total_text})")

if not stocks:
print("本次没有采集到有效数据,数据库未做修改。")
connection.close()
return

snapshot_time = time.strftime("%Y-%m-%d %H:%M:%S")
save_stocks(connection, stocks, source, snapshot_time)
print(f"[写库] 已写入 {DB_PATH}")

show_database(connection)
connection.close()

if name == "main":
main()

**作业③ university.py**
# -*- coding: utf-8 -*-
"""
作业③:爬取软科中国大学排名 2021 主榜( https://www.shanghairanking.cn/rankings/bcur/2021 )
      全部院校信息,并保存到 SQLite 数据库。

抓包分析(F12 -> Network -> XHR)
排名页面本身是前端渲染的,HTML 里没有学校数据,真正的数据来自下面的 JSON 接口:
https://www.shanghairanking.cn/api/pub/v1/bcur?bcur_type=11&year=2021
参数说明:
bcur_type 榜单类型,11 表示“主榜”(综合类、理工类、师范类、农业类、林业类)
year 榜单年份
返回结构:
{"code":200,"data":{"rankings":[
{"rankOverall":"1","univNameCn":"清华大学","univNameEn":"Tsinghua University",
"univCategory":"综合","province":"北京","score":"969.2", ...}, ...]}}
2021 主榜共 582 所院校,接口一次返回全部,不需要翻页。

运行方式
python university.py
数据库文件 university.db 会生成在本脚本所在目录(与运行目录无关)。
"""

import os
import sqlite3
import time
import unicodedata

import requests

==================== 基础配置 ====================

BASE_DIR = os.path.dirname(os.path.abspath(file))
DB_PATH = os.path.join(BASE_DIR, "university.db")

软科排名数据接口

API_URL = "https://www.shanghairanking.cn/api/pub/v1/bcur"

请求参数:bcur_type=11 是主榜,year=2021 是 2021 年

PARAMS = {"bcur_type": 11, "year": 2021}

请求头:Referer 必须是排名页,否则接口可能返回 403

HEADERS = {
"User-Agent": (
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
"AppleWebKit/537.36 (KHTML, like Gecko) "
"Chrome/130.0.0.0 Safari/537.36"
),
"Referer": "https://www.shanghairanking.cn/rankings/bcur/2021",
}

YEAR = 2021
REQUEST_RETRY = 3 # 最多请求次数
REQUEST_TIMEOUT = 30 # 单次请求超时时间(秒)

==================== 终端表格对齐工具 ====================

def display_width(text):
"""计算字符串在终端里的显示宽度:中日韩全角字符占 2 格,其它占 1 格。"""
width = 0
for char in str(text):
width += 2 if unicodedata.east_asian_width(char) in ("W", "F") else 1
return width

def pad(text, width, align="<"):
"""按显示宽度补齐空格,保证中文表格不会错列。align 取 '<' 左对齐、'>' 右对齐。"""
text = "" if text is None else str(text)
blank = " " * max(width - display_width(text), 0)
return blank + text if align == ">" else text + blank

def format_row(cells):
"""把若干 (内容, 宽度, 对齐) 单元格拼成一行,列与列之间留一个空格。"""
return " ".join(pad(text, width, align) for text, width, align in cells)

==================== 数据抓取 ====================

def fetch_rankings():
"""请求排名接口并返回 rankings 列表,失败时重试,全部失败返回空列表。"""
print(f"[请求] {API_URL} 参数:{PARAMS}")

for attempt in range(1, REQUEST_RETRY + 1):
try:
response = requests.get(
API_URL, params=PARAMS, headers=HEADERS, timeout=REQUEST_TIMEOUT
)
response.raise_for_status()
result = response.json()

rankings = result.get("data", {}).get("rankings") or []
if rankings:
print(f"[响应] 接口返回 {len(rankings)} 所院校")
return rankings

print(f" 第 {attempt} 次请求返回空列表,返回内容:{str(result)[:200]}")
except (requests.RequestException, ValueError) as error:
print(f" 第 {attempt} 次请求失败:{error}")

if attempt < REQUEST_RETRY:
time.sleep(attempt * 2) # 退避等待后再试

return []

def to_int_rank(rank_text):
"""把排名文本转成整数;'1'、'1.0'、'1(并列)' 之类都能取到数字,取不到返回 None。"""
digits = ""
for char in str(rank_text):
if char.isdigit():
digits += char
elif digits:
break
return int(digits) if digits else None

def to_float_score(score_text):
"""把总评分转成 float,无效值返回 None。"""
try:
return float(score_text)
except (TypeError, ValueError):
return None

def parse_rankings(rankings, crawl_time):
"""
把接口返回的原始 JSON 转成数据库记录。

字段映射:rankOverall -> 排名、univNameCn -> 学校、univNameEn -> 英文名、
province -> 省市、univCategory -> 类型、score -> 总分
排名或校名为空、以及重复校名的记录会被跳过。
"""
records = []
seen_names = set()

for item in rankings:
name = str(item.get("univNameCn") or "").strip()
rank = to_int_rank(item.get("rankOverall"))
score = to_float_score(item.get("score"))

if not name or rank is None or name in seen_names:
continue

seen_names.add(name)
records.append({
"rank": rank,
"name": name,
"english_name": str(item.get("univNameEn") or "").strip(),
"province": str(item.get("province") or "").strip(),
"school_type": str(item.get("univCategory") or "").strip(),
"score": score,
"year": YEAR,
"source_url": f"{API_URL}?bcur_type={PARAMS['bcur_type']}&year={YEAR}",
"crawl_time": crawl_time,
})

return records

==================== 数据库操作 ====================

def create_table(connection):
"""创建大学排名表;(year, name) 唯一,重复采集时更新而不是新增。"""
connection.execute("""
CREATE TABLE IF NOT EXISTS universities (
id INTEGER PRIMARY KEY AUTOINCREMENT,
rank INTEGER NOT NULL,
name TEXT NOT NULL,
english_name TEXT,
province TEXT,
school_type TEXT,
score REAL,
year INTEGER NOT NULL,
source_url TEXT,
crawl_time TEXT NOT NULL,
UNIQUE (year, name)
)
""")
connection.commit()

def save_rankings(connection, records):
"""批量写入;主键冲突时更新分数、排名等信息,保证 id 稳定、不产生重复行。"""
with connection: # with 块正常结束自动 commit,异常自动 rollback
connection.executemany("""
INSERT INTO universities (
rank, name, english_name, province, school_type,
score, year, source_url, crawl_time
) VALUES (
:rank, :name, :english_name, :province, :school_type,
:score, :year, :source_url, :crawl_time
)
ON CONFLICT(year, name) DO UPDATE SET
rank = excluded.rank,
english_name = excluded.english_name,
province = excluded.province,
school_type = excluded.school_type,
score = excluded.score,
source_url = excluded.source_url,
crawl_time = excluded.crawl_time
""", records)

def show_ranking(connection, top=20):
"""按作业要求的五列(排名/学校/省市/类型/总分)打印榜单和统计信息。"""
rows = connection.execute("""
SELECT rank, name, province, school_type, score
FROM universities
WHERE year = ?
ORDER BY rank ASC
""", (YEAR,)).fetchall()

列定义:(表头, 宽度, 对齐),行与表头共用,保证对齐一致

columns = [("排名", 5, ">"), ("学校", 26, "<"), ("省市", 8, "<"), ("类型", 8, "<"), ("总分", 8, ">")]
line = "=" * (sum(width for _, width, _ in columns) + len(columns) - 1)

print("\n" + "=" * len(line))
print(f"软科中国大学排名 {YEAR} 主榜(数据库 university.universities 表)")
print("=" * len(line))
print(format_row([(title, width, align) for title, width, align in columns]))
print("-" * len(line))

def print_one(rank_value, name_value, province_value, type_value, score_value):
"""打印一行榜单数据,五列与作业要求一致。"""
print(format_row([
(rank_value, 5, ">"),
(name_value, 26, "<"),
(province_value, 8, "<"),
(type_value, 8, "<"),
(f"{score_value:.1f}" if score_value is not None else "-", 8, ">"),
]))

for rank, name, province, school_type, score in rows[:top]:
print_one(rank, name, province, school_type, score)

if len(rows) > top:
print(f"…… 中间 {len(rows) - top - 3} 条省略,完整 {len(rows)} 条已存入数据库 ……")
for rank, name, province, school_type, score in rows[-3:]:
print_one(rank, name, province, school_type, score)

print("-" * len(line))

统计信息:院校总数、类型分布、前 5 个省份

type_rows = connection.execute("""
SELECT school_type, COUNT() FROM universities
WHERE year = ? GROUP BY school_type ORDER BY COUNT(
) DESC
""", (YEAR,)).fetchall()
province_rows = connection.execute("""
SELECT province, COUNT() FROM universities
WHERE year = ? GROUP BY province ORDER BY COUNT(
) DESC LIMIT 5
""", (YEAR,)).fetchall()
average = connection.execute(
"SELECT AVG(score) FROM universities WHERE year = ?", (YEAR,)
).fetchone()[0]

print(f"院校总数:{len(rows)} 所 平均总分:{average:.2f}")
print("类型分布:" + " ".join(f"{name} {count} 所" for name, count in type_rows))
print("院校最多的 5 个省市:" + " ".join(f"{name} {count} 所" for name, count in province_rows))

==================== 主流程 ====================

def main():
"""程序入口:抓取 -> 解析 -> 写库 -> 展示。"""
crawl_time = time.strftime("%Y-%m-%d %H:%M:%S")

print("=" * 78)
print(f"作业③ 软科中国大学排名 {YEAR} 主榜数据爬取")
print(f"采集时间:{crawl_time}")
print("=" * 78)

connection = sqlite3.connect(DB_PATH)
create_table(connection)

rankings = fetch_rankings()
if not rankings:
print("\n没有获取到排名数据,数据库未做修改。")
connection.close()
return

records = parse_rankings(rankings, crawl_time)
print(f"[解析] 有效记录 {len(records)} 条(跳过空值或重复校名 {len(rankings) - len(records)} 条)")

if not records:
print("解析后没有有效数据,数据库未做修改。")
connection.close()
return

save_rankings(connection, records)
print(f"[写库] 本次写入 {len(records)} 条记录 -> {DB_PATH}")

show_ranking(connection)
connection.close()

if name == "main":
main()

### **运行结果:**

作业②终端输出(10 页共 1000 只股票,按涨跌幅排序打印前 20,并统计涨跌家数):

股票爬虫运行结果:

775eb2f479133392d6f3ba2c9a85afd4

数据库 stocks 表:

13adff66d218328a638e76068b2f896b
全部数据见gitee的csv文件

作业③的 F12 调试分析过程(Network 面板中过滤 bcur,点开请求查看 Preview / Response 中的 JSON):

F12抓包分析过程:

03_F12抓包分析过程

作业③终端输出(582 所院校,按五列打印前 20 与最后 3 名,并统计类型与省份分布):

大学排名爬虫运行结果:

ee36b3c37aef3284f31c82185c0c5e72

数据库 universities 表:
a828c48d35bc0627a85632efa6b20cd9

全部数据见gitee的csv文件

二.心得体会

通过这两个实验,我熟悉了用 F12 抓包分析网页数据来源的方法。对于前端渲染的页面,直接请求 HTML 取不到数据,需要先找到浏览器实际调用的 JSON 接口,再按接口参数请求并解析,这比解析网页结构更稳定,返回的也是结构化数据。

在爬取股票接口的过程中,我遇到了接口限流导致的连接被断开,认识到爬虫除了请求和解析,还需要考虑重试、退避和备用数据源,以及用事务保证写入失败时不破坏已有数据。在爬取软科排名时,通过对比接口返回的院校数量和类型分布,确认了抓到的是 2021 主榜而不是其他榜单,让我体会到采集完成后核对数据的重要性。

作业总结

通过本次作业,我完成了天气预报、股票信息和大学排名三类数据的采集,进一步熟悉了 requests、BeautifulSoup 和 json 解析的使用。三类数据的获取方式并不相同:天气预报的数据写在 HTML 中,需要解析页面结构;股票和大学排名的数据由前端请求接口得到,需要先抓包再解析 JSON。实验过程中也遇到了相对日期、接口限流、字段单位不统一等问题,通过实际调试让我更加了解了网页数据采集的完整流程。

整体来看,本次作业让我掌握了从确定数据来源到请求、解析、清洗和入库的基本方法,也提高了自己分析网页结构、处理接口限制和核对数据的能力。

posted @ 2026-11-17 20:26  好的id  阅读(9)  评论(0)    收藏  举报