作业1
在中国气象网( http://www.weather.com.cn )给定城市集【3-5个城市】的7日天气预报
完整代码
from __future__ import annotations
import argparse
import re
import sqlite3
import sys
import time
from datetime import date, datetime, timedelta
from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple
import requests
from bs4 import BeautifulSoup
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
BASE_DIR = Path(__file__).resolve().parent
DEFAULT_DB_PATH = BASE_DIR / "data" / "weather.db"
URL_TEMPLATE = "https://www.weather.com.cn/weather/{city_code}.shtml"
CITIES: Tuple[Dict[str, str], ...] = (
{"code": "101010100", "name": "北京", "province": "北京"},
{"code": "101020100", "name": "上海", "province": "上海"},
{"code": "101280101", "name": "广州", "province": "广东"},
{"code": "101270101", "name": "成都", "province": "四川"},
{"code": "101050101", "name": "哈尔滨", "province": "黑龙江"},
)
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 build_session() -> requests.Session:
session = requests.Session()
retry = Retry(
total=3,
connect=3,
read=3,
backoff_factor=0.8,
status_forcelist=(429, 500, 502, 503, 504),
allowed_methods=frozenset({"GET"}),
)
adapter = HTTPAdapter(max_retries=retry)
session.mount("https://", adapter)
session.mount("http://", adapter)
session.headers.update(
{
"User-Agent": USER_AGENT,
"Accept-Language": "zh-CN,zh;q=0.9",
"Referer": "https://www.weather.com.cn/",
}
)
return session
def fetch_html(session: requests.Session, url: str, timeout: int = 20) -> str:
"""请求页面并返回文本,自动识别网页编码。"""
response = session.get(url, timeout=timeout)
response.raise_for_status()
# 气象网页面声明为 UTF-8;apparent_encoding 可兼容个别子页面。
response.encoding = response.apparent_encoding or "utf-8"
return response.text
def _to_int(value: str) -> Optional[int]:
"""从 ``14``、``-3℃`` 之类的文本中提取整数。"""
match = re.search(r"-?\d+", value or "")
return int(match.group()) if match else None
def parse_forecasts(
html: str, city: Dict[str, str]
) -> Tuple[str, List[Dict[str, Any]]]:
soup = BeautifulSoup(html, "html.parser")
items = soup.select("ul.t.clearfix > li")
if not items:
raise ValueError(f"{city['name']} 页面中未找到 7 日预报节点")
update_node = soup.select_one("#update_time")
update_time = update_node.get("value", "").strip() if update_node else ""
# 页面上的日期只有“6日(今天)”这样的文本,这里以抓取当天为基准推算完整日期。
today = date.today()
forecasts: List[Dict[str, Any]] = []
for offset, item in enumerate(items[:7]):
date_node = item.select_one("h1")
date_text = date_node.get_text(strip=True) if date_node else ""
label_match = re.search(r"((.+?))", date_text)
date_label = label_match.group(1) if label_match else date_text
weather_node = item.select_one("p.wea")
weather = weather_node.get_text(strip=True) if weather_node else ""
temp_node = item.select_one("p.tem")
temp_high: Optional[int] = None
temp_low: Optional[int] = None
if temp_node:
high_node = temp_node.select_one("span")
low_node = temp_node.select_one("i")
if high_node:
temp_high = _to_int(high_node.get_text(strip=True))
if low_node:
temp_low = _to_int(low_node.get_text(strip=True))
# 风向节点形如 <span title="东南风">,白天、夜间各一个。
wind_nodes = item.select("p.win em span")
wind_dirs = [node.get("title", "").strip() for node in wind_nodes]
while len(wind_dirs) < 2:
wind_dirs.append("")
wind_level_node = item.select_one("p.win i")
wind_level = wind_level_node.get_text(strip=True) if wind_level_node else ""
forecasts.append(
{
"forecast_date": (today + timedelta(days=offset)).isoformat(),
"date_label": date_label,
"weather": weather,
"temp_high": temp_high,
"temp_low": temp_low,
"wind_dir_day": wind_dirs[0],
"wind_dir_night": wind_dirs[1],
"wind_level": wind_level,
"update_time": update_time,
}
)
return update_time, forecasts
def init_db(conn: sqlite3.Connection) -> None:
conn.executescript(
"""
CREATE TABLE IF NOT EXISTS city (
id INTEGER PRIMARY KEY AUTOINCREMENT,
city_code TEXT NOT NULL UNIQUE,
city_name TEXT NOT NULL,
province TEXT NOT NULL,
source_url TEXT NOT NULL,
created_at TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS weather_forecast (
id INTEGER PRIMARY KEY AUTOINCREMENT,
city_id INTEGER NOT NULL,
forecast_date TEXT NOT NULL,
date_label TEXT,
weather TEXT,
temp_high INTEGER,
temp_low INTEGER,
wind_dir_day TEXT,
wind_dir_night TEXT,
wind_level TEXT,
update_time TEXT,
crawl_time TEXT NOT NULL,
UNIQUE (city_id, forecast_date),
FOREIGN KEY (city_id) REFERENCES city (id) ON DELETE CASCADE
);
CREATE INDEX IF NOT EXISTS idx_forecast_date
ON weather_forecast (forecast_date);
"""
)
conn.commit()
def save_forecasts(
conn: sqlite3.Connection,
city: Dict[str, str],
forecasts: List[Dict[str, Any]],
source_url: str,
) -> int:
now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
with conn: # with 语句自动提交事务,异常时回滚
conn.execute(
"""
INSERT INTO city (city_code, city_name, province, source_url, created_at)
VALUES (?, ?, ?, ?, ?)
ON CONFLICT (city_code) DO UPDATE SET
city_name = excluded.city_name,
province = excluded.province,
source_url = excluded.source_url
""",
(city["code"], city["name"], city["province"], source_url, now),
)
city_id = conn.execute(
"SELECT id FROM city WHERE city_code = ?", (city["code"],)
).fetchone()["id"]
rows = [
(
city_id,
item["forecast_date"],
item["date_label"],
item["weather"],
item["temp_high"],
item["temp_low"],
item["wind_dir_day"],
item["wind_dir_night"],
item["wind_level"],
item["update_time"],
now,
)
for item in forecasts
]
conn.executemany(
"""
INSERT INTO weather_forecast (
city_id, forecast_date, date_label, weather,
temp_high, temp_low, wind_dir_day, wind_dir_night,
wind_level, update_time, crawl_time
)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT (city_id, forecast_date) DO UPDATE SET
date_label = excluded.date_label,
weather = excluded.weather,
temp_high = excluded.temp_high,
temp_low = excluded.temp_low,
wind_dir_day = excluded.wind_dir_day,
wind_dir_night = excluded.wind_dir_night,
wind_level = excluded.wind_level,
update_time = excluded.update_time,
crawl_time = excluded.crawl_time
""",
rows,
)
return len(rows)
def parse_args() -> argparse.Namespace:
"""解析命令行参数。"""
parser = argparse.ArgumentParser(description="爬取中国气象网 7 日天气预报")
parser.add_argument(
"--db",
type=Path,
default=DEFAULT_DB_PATH,
help=f"SQLite 数据库路径(默认:{DEFAULT_DB_PATH})",
)
parser.add_argument(
"--delay",
type=float,
default=0.8,
help="每个城市之间的请求间隔(秒),默认 0.8",
)
return parser.parse_args()
def main() -> int:
args = parse_args()
args.db.parent.mkdir(parents=True, exist_ok=True)
session = build_session()
conn = sqlite3.connect(args.db)
conn.row_factory = sqlite3.Row
conn.execute("PRAGMA foreign_keys = ON")
init_db(conn)
success = 0
total_rows = 0
try:
for index, city in enumerate(CITIES, start=1):
url = URL_TEMPLATE.format(city_code=city["code"])
print(f"[{index}/{len(CITIES)}] 正在抓取 {city['name']}:{url}")
try:
html = fetch_html(session, url)
update_time, forecasts = parse_forecasts(html, city)
count = save_forecasts(conn, city, forecasts, url)
success += 1
total_rows += count
print(f" 更新时间:{update_time or '未知'},写入 {count} 条")
for forecast in forecasts:
print(
" {date} {label:<4} {weather:<10} "
"{high:>3}/{low:>3}℃ {wind_day}/{wind_night} {level}".format(
date=forecast["forecast_date"],
label=forecast["date_label"],
weather=forecast["weather"],
high=forecast["temp_high"]
if forecast["temp_high"] is not None
else "-",
low=forecast["temp_low"]
if forecast["temp_low"] is not None
else "-",
wind_day=forecast["wind_dir_day"] or "-",
wind_night=forecast["wind_dir_night"] or "-",
level=forecast["wind_level"] or "-",
)
)
except (requests.RequestException, ValueError) as exc:
print(f" [失败] {exc}", file=sys.stderr)
if index < len(CITIES):
# 控制请求频率,避免给目标网站造成压力。
time.sleep(max(0.0, args.delay))
finally:
conn.close()
print("-" * 64)
print(f"完成:{success}/{len(CITIES)} 个城市,共 {total_rows} 条预报")
print(f"数据库:{args.db.resolve()}")
return 0 if success == len(CITIES) else 1
if __name__ == "__main__":
if hasattr(sys.stdout, "reconfigure"):
sys.stdout.reconfigure(encoding="utf-8")
if hasattr(sys.stderr, "reconfigure"):
sys.stderr.reconfigure(encoding="utf-8")
raise SystemExit(main())
结果展示
D:\flask_wangkeren\.venv\Scripts\python.exe D:\flask_wangkeren\102402104wkr\20261106\one.py
[1/5] 正在抓取 北京:https://www.weather.com.cn/weather/101010100.shtml
更新时间:07:30,写入 7 条
2026-11-06 今天 晴转多云 14/ 2℃ 东南风/东北风 <3级
2026-11-07 明天 小雨转雨夹雪 5/ 0℃ 北风/北风 <3级
2026-11-08 后天 雨夹雪转晴 5/ -3℃ 东北风/西北风 <3级
2026-11-09 周一 晴 9/ 0℃ 南风/北风 <3级
2026-11-10 周二 晴 12/ 0℃ 南风/北风 <3级
2026-11-11 周三 晴 14/ 2℃ 西北风/北风 <3级
2026-11-12 周四 晴 14/ 2℃ 西南风/北风 <3级
[2/5] 正在抓取 上海:https://www.weather.com.cn/weather/101020100.shtml
更新时间:07:30,写入 7 条
2026-11-06 今天 阴转多云 18/ 15℃ 东北风/东风 <3级
2026-11-07 明天 阴转小雨 20/ 15℃ 东风/东风 <3级
2026-11-08 后天 小雨 17/ 13℃ 东南风/西北风 <3级
2026-11-09 周一 小雨转多云 15/ 8℃ 北风/西北风 3-4级转<3级
2026-11-10 周二 多云 15/ 9℃ 北风/北风 <3级
2026-11-11 周三 阴转多云 17/ 12℃ 东北风/东风 <3级
2026-11-12 周四 阴 20/ 14℃ 东南风/东风 <3级
[3/5] 正在抓取 广州:https://www.weather.com.cn/weather/101280101.shtml
更新时间:07:30,写入 7 条
2026-11-06 今天 小雨转多云 31/ 21℃ 无持续风向/无持续风向 <3级
2026-11-07 明天 多云转晴 30/ 22℃ 无持续风向/无持续风向 <3级
2026-11-08 后天 多云 31/ 18℃ 无持续风向/北风 <3级转3-4级
2026-11-09 周一 多云 25/ 15℃ 北风/无持续风向 3-4级转<3级
2026-11-10 周二 多云 23/ 14℃ 无持续风向/无持续风向 <3级
2026-11-11 周三 多云 24/ 16℃ 无持续风向/无持续风向 <3级
2026-11-12 周四 多云转阴 26/ 19℃ 无持续风向/无持续风向 <3级
[4/5] 正在抓取 成都:https://www.weather.com.cn/weather/101270101.shtml
更新时间:07:30,写入 7 条
2026-11-06 今天 多云转阴 21/ 14℃ 无持续风向/无持续风向 <3级
2026-11-07 明天 小雨 20/ 12℃ 无持续风向/无持续风向 <3级
2026-11-08 后天 阴转多云 21/ 10℃ 无持续风向/无持续风向 <3级
2026-11-09 周一 多云转阴 22/ 11℃ 无持续风向/无持续风向 <3级
2026-11-10 周二 多云 20/ 10℃ 无持续风向/无持续风向 <3级
2026-11-11 周三 多云转小雨 18/ 11℃ 无持续风向/无持续风向 <3级
2026-11-12 周四 小雨 18/ 12℃ 无持续风向/无持续风向 <3级
[5/5] 正在抓取 哈尔滨:https://www.weather.com.cn/weather/101050101.shtml
更新时间:07:30,写入 7 条
2026-11-06 今天 多云转晴 -6/-12℃ 西北风/西北风 4-5级转3-4级
2026-11-07 明天 晴 -5/-13℃ 西北风/西风 3-4级转<3级
2026-11-08 后天 晴 -2/-12℃ 西风/西北风 3-4级转<3级
2026-11-09 周一 晴 -5/-14℃ 西北风/东南风 3-4级转<3级
2026-11-10 周二 多云 0/ -9℃ 东南风/南风 3-4级转<3级
2026-11-11 周三 多云转晴 6/ -2℃ 西南风/西南风 3-4级
2026-11-12 周四 多云转晴 10/ -3℃ 西南风/西风 4-5级转3-4级
----------------------------------------------------------------
完成:5/5 个城市,共 35 条预报
数据库:D:\flask_wangkeren\102402104wkr\20261106\data\weather.db
Process finished with exit code 0

心得体会
这次作业让我第一次完整走完了“请求—解析—清洗—入库”的流程。以前写爬虫只关心能不能抓到,这次把数据库唯一键和 UPSERT 加上之后,才真正理解“可重复运行”比“能跑一次”重要。
BeautifulSoup 的 CSS 选择器比正则直观很多,但依赖页面结构。气象网把 7 日预报放在 ul.t.clearfix > li 中,如果页面改版,选择器就要跟着改。为此我把解析失败包装成 ValueError,让程序明确报错,而不是悄悄写入空数据。
日期推算是一个容易忽略的细节。页面只给“今天、明天、周一”,如果直接存文本,后面无法按日期查询。我用 date.today() 加 timedelta 生成 ISO 日期,同时保留 date_label 方便阅读。
SQLite 的 with conn 会自动提交或回滚,配合 executemany 和 ON CONFLICT,代码比手写 commit/rollback 清晰很多。外键和唯一索引也让数据关系更可靠。
还可以改进的地方:把城市列表做成配置文件;对页面编码做更稳健的检测;增加重试次数和日志文件;把 SQLite 换成 MySQL 以支持多机部署。
最后,爬虫要控制频率。5 个城市之间加 0.8 秒延迟,既不影响结果,也不会给目标站点造成压力。
作业2
用requests和json解析方法定向爬取股票相关信息
完整代码
from __future__ import annotations
import argparse
import json
import sqlite3
import sys
from dataclasses import dataclass
from datetime import datetime
from pathlib import Path
from typing import Any, Dict, Iterable, List, Optional, Tuple
import requests
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
BASE_DIR = Path(__file__).resolve().parent
DEFAULT_DB_PATH = BASE_DIR / "data" / "stock.db"
EASTMONEY_API = "https://push2.eastmoney.com/api/qt/clist/get"
EASTMONEY_HISTORY_API = "https://push2his.eastmoney.com/api/qt/stock/kline/get"
SINA_API = (
"https://vip.stock.finance.sina.com.cn/quotes_service/api/json_v2.php/"
"Market_Center.getHQNodeData"
)
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"
)
EASTMONEY_MARKETS = "m:0+t:6,m:0+t:80,m:1+t:2,m:1+t:23"
EASTMONEY_FIELDS = (
"f2,f3,f4,f5,f6,f7,f8,f9,f10,f12,f13,f14,"
"f15,f16,f17,f18,f20,f21,f23"
)
@dataclass
class StockRecord:
code: str
name: str
market: str
price: Optional[float] = None
change_amount: Optional[float] = None
change_pct: Optional[float] = None
open: Optional[float] = None
high: Optional[float] = None
low: Optional[float] = None
prev_close: Optional[float] = None
volume: Optional[int] = None
amount: Optional[float] = None
turnover_rate: Optional[float] = None
pe: Optional[float] = None
pb: Optional[float] = None
total_market_cap: Optional[float] = None
float_market_cap: Optional[float] = None
quote_time: str = ""
source: str = ""
rank_no: int = 0
def build_session() -> requests.Session:
session = requests.Session()
retry = Retry(
total=3,
connect=3,
read=3,
backoff_factor=0.8,
status_forcelist=(429, 500, 502, 503, 504),
allowed_methods=frozenset({"GET"}),
)
adapter = HTTPAdapter(max_retries=retry)
session.mount("https://", adapter)
session.mount("http://", adapter)
session.headers.update(
{
"User-Agent": USER_AGENT,
"Accept": "application/json, text/plain, */*",
"Accept-Language": "zh-CN,zh;q=0.9",
}
)
return session
def to_float(value: Any) -> Optional[float]:
if value is None:
return None
text = str(value).strip().replace(",", "")
if text in {"", "-", "--", "None", "null"}:
return None
try:
return float(text)
except ValueError:
return None
def to_int(value: Any) -> Optional[int]:
number = to_float(value)
return int(number) if number is not None else None
def fetch_eastmoney(session: requests.Session, limit: int) -> List[StockRecord]:
params = {
"pn": 1,
"pz": limit,
"po": 1,
"np": 1,
"ut": "bd1d9ddb04089700cf9c27f6f7426281",
"fltt": 2,
"invt": 2,
"fid": "f6",
"fs": EASTMONEY_MARKETS,
"fields": EASTMONEY_FIELDS,
}
response = session.get(
EASTMONEY_API,
params=params,
headers={"Referer": "https://quote.eastmoney.com/"},
timeout=20,
)
response.raise_for_status()
payload = response.json()
diff = (payload.get("data") or {}).get("diff") or []
records: List[StockRecord] = []
for rank_no, item in enumerate(diff, start=1):
code = str(item.get("f12", "")).strip()
name = str(item.get("f14", "")).strip()
if not code or not name:
continue
volume_hands = to_float(item.get("f5"))
volume = int(volume_hands * 100) if volume_hands is not None else None
records.append(
StockRecord(
code=code,
name=name,
market="沪市" if to_int(item.get("f13")) == 1 else "深市",
price=to_float(item.get("f2")),
change_amount=to_float(item.get("f4")),
change_pct=to_float(item.get("f3")),
open=to_float(item.get("f17")),
high=to_float(item.get("f15")),
low=to_float(item.get("f16")),
prev_close=to_float(item.get("f18")),
volume=volume,
amount=to_float(item.get("f6")),
turnover_rate=to_float(item.get("f8")),
pe=to_float(item.get("f9")),
pb=to_float(item.get("f23")),
total_market_cap=to_float(item.get("f20")),
float_market_cap=to_float(item.get("f21")),
quote_time=datetime.now().strftime("%H:%M:%S"),
source="eastmoney",
rank_no=rank_no,
)
)
return records
def fetch_eastmoney_history(
session: requests.Session, limit: int
) -> List[StockRecord]:
universe_params = {
"pn": 1,
"pz": 100,
"po": 1,
"np": 1,
"ut": "bd1d9ddb04089700cf9c27f6f7426281",
"fltt": 2,
"invt": 2,
"fid": "f20",
"fs": EASTMONEY_MARKETS,
"fields": "f9,f12,f13,f14,f20,f21,f23",
}
response = session.get(
EASTMONEY_API,
params=universe_params,
headers={"Referer": "https://quote.eastmoney.com/"},
timeout=20,
)
response.raise_for_status()
universe = (response.json().get("data") or {}).get("diff") or []
records: List[StockRecord] = []
for index, item in enumerate(universe, start=1):
code = str(item.get("f12", "")).strip()
name = str(item.get("f14", "")).strip()
if not code or not name:
continue
secid = f"{to_int(item.get('f13')) or 0}.{code}"
kline_params = {
"secid": secid,
"klt": "101",
"fqt": "1",
"lmt": "2",
"end": "20500101",
"fields1": "f1,f2,f3,f4,f5,f6",
"fields2": "f51,f52,f53,f54,f55,f56,f57,f58,f59,f60,f61",
}
try:
payload = session.get(
EASTMONEY_HISTORY_API,
params=kline_params,
headers={"Referer": "https://quote.eastmoney.com/"},
timeout=15,
).json()
klines = (payload.get("data") or {}).get("klines") or []
if not klines:
continue
latest = klines[-1].split(",")
previous_close = None
if len(klines) >= 2:
previous_close = to_float(klines[-2].split(",")[2])
elif payload["data"].get("preKPrice") is not None:
previous_close = to_float(payload["data"]["preKPrice"])
volume_hands = to_float(latest[5])
records.append(
StockRecord(
code=code,
name=name,
market="沪市" if to_int(item.get("f13")) == 1 else "深市",
price=to_float(latest[2]),
change_amount=to_float(latest[9]),
change_pct=to_float(latest[8]),
open=to_float(latest[1]),
high=to_float(latest[3]),
low=to_float(latest[4]),
prev_close=previous_close,
volume=int(volume_hands * 100)
if volume_hands is not None
else None,
amount=to_float(latest[6]),
turnover_rate=to_float(latest[10]),
pe=to_float(item.get("f9")),
pb=to_float(item.get("f23")),
total_market_cap=to_float(item.get("f20")),
float_market_cap=to_float(item.get("f21")),
quote_time=latest[0],
source="eastmoney_history",
rank_no=0,
)
)
except (requests.RequestException, ValueError, KeyError, IndexError):
continue
if index % 20 == 0:
print(f" 历史行情进度:{index}/{len(universe)}")
records.sort(key=lambda record: record.amount or 0, reverse=True)
for rank_no, record in enumerate(records[:limit], start=1):
record.rank_no = rank_no
return records[:limit]
def fetch_sina(session: requests.Session, limit: int) -> List[StockRecord]:
params = {
"page": 1,
"num": limit,
"sort": "amount",
"asc": 0,
"node": "hs_a",
"symbol": "",
"_s_r_a": "page",
}
response = session.get(
SINA_API,
params=params,
headers={"Referer": "https://finance.sina.com.cn/stock/"},
timeout=20,
)
response.raise_for_status()
text = response.text.strip()
if text.startswith("(") and text.endswith(")"):
text = text[1:-1]
items = json.loads(text)
if not isinstance(items, list):
raise ValueError("新浪接口返回格式异常")
records: List[StockRecord] = []
for rank_no, item in enumerate(items, start=1):
code = str(item.get("code", "")).strip()
name = str(item.get("name", "")).strip()
if not code or not name:
continue
symbol = str(item.get("symbol", "")).lower()
market = {"sh": "沪市", "sz": "深市", "bj": "北交所"}.get(
symbol[:2], "未知"
)
total_market_cap = to_float(item.get("mktcap"))
float_market_cap = to_float(item.get("nmc"))
if total_market_cap is not None:
total_market_cap *= 10000
if float_market_cap is not None:
float_market_cap *= 10000
records.append(
StockRecord(
code=code,
name=name,
market=market,
price=to_float(item.get("trade")),
change_amount=to_float(item.get("pricechange")),
change_pct=to_float(item.get("changepercent")),
open=to_float(item.get("open")),
high=to_float(item.get("high")),
low=to_float(item.get("low")),
prev_close=to_float(item.get("settlement")),
volume=to_int(item.get("volume")),
amount=to_float(item.get("amount")),
turnover_rate=to_float(item.get("turnoverratio")),
pe=to_float(item.get("per")),
pb=to_float(item.get("pb")),
total_market_cap=total_market_cap,
float_market_cap=float_market_cap,
quote_time=str(item.get("ticktime", "")),
source="sina",
rank_no=rank_no,
)
)
return records
def has_valid_quotes(records: List[StockRecord]) -> bool:
valid = sum(1 for record in records if record.price and record.price > 0)
return bool(records) and valid >= max(3, len(records) // 2)
def fetch_records(
session: requests.Session, limit: int, source: str
) -> Tuple[List[StockRecord], str]:
if source == "eastmoney":
return fetch_eastmoney(session, limit), "eastmoney"
if source == "sina":
return fetch_sina(session, limit), "sina"
if source == "history":
return fetch_eastmoney_history(session, limit), "eastmoney_history"
eastmoney_records: List[StockRecord] = []
try:
eastmoney_records = fetch_eastmoney(session, limit)
except (requests.RequestException, ValueError, KeyError) as exc:
print(f"[警告] 东方财富接口请求失败:{exc}", file=sys.stderr)
if has_valid_quotes(eastmoney_records):
return eastmoney_records, "eastmoney"
print(
"[提示] 东方财富接口当前有效报价不足(盘前/闭市时常见),"
"尝试新浪股票接口。",
file=sys.stderr,
)
try:
sina_records = fetch_sina(session, limit)
except (requests.RequestException, ValueError, KeyError) as exc:
print(f"[警告] 新浪接口请求失败:{exc}", file=sys.stderr)
sina_records = []
if has_valid_quotes(sina_records):
return sina_records, "sina"
print(
"[提示] 新浪接口盘前报价也为 0,改用东方财富日 K 线接口"
"获取上一交易日收盘行情。",
file=sys.stderr,
)
return fetch_eastmoney_history(session, limit), "eastmoney_history"
def init_db(conn: sqlite3.Connection) -> None:
conn.executescript(
"""
CREATE TABLE IF NOT EXISTS stock_quote (
code TEXT PRIMARY KEY,
name TEXT NOT NULL,
market TEXT,
price REAL,
change_amount REAL,
change_pct REAL,
open REAL,
high REAL,
low REAL,
prev_close REAL,
volume INTEGER,
amount REAL,
turnover_rate REAL,
pe REAL,
pb REAL,
total_market_cap REAL,
float_market_cap REAL,
quote_time TEXT,
source TEXT NOT NULL,
rank_no INTEGER,
crawl_time TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_stock_amount
ON stock_quote (amount DESC);
"""
)
conn.commit()
def save_records(
conn: sqlite3.Connection, records: Iterable[StockRecord]
) -> int:
now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
rows = [
(
record.code,
record.name,
record.market,
record.price,
record.change_amount,
record.change_pct,
record.open,
record.high,
record.low,
record.prev_close,
record.volume,
record.amount,
record.turnover_rate,
record.pe,
record.pb,
record.total_market_cap,
record.float_market_cap,
record.quote_time,
record.source,
record.rank_no,
now,
)
for record in records
]
with conn:
conn.execute("DELETE FROM stock_quote")
conn.executemany(
"""
INSERT INTO stock_quote (
code, name, market, price, change_amount, change_pct,
open, high, low, prev_close, volume, amount,
turnover_rate, pe, pb, total_market_cap, float_market_cap,
quote_time, source, rank_no, crawl_time
)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT (code) DO UPDATE SET
name = excluded.name,
market = excluded.market,
price = excluded.price,
change_amount = excluded.change_amount,
change_pct = excluded.change_pct,
open = excluded.open,
high = excluded.high,
low = excluded.low,
prev_close = excluded.prev_close,
volume = excluded.volume,
amount = excluded.amount,
turnover_rate = excluded.turnover_rate,
pe = excluded.pe,
pb = excluded.pb,
total_market_cap = excluded.total_market_cap,
float_market_cap = excluded.float_market_cap,
quote_time = excluded.quote_time,
source = excluded.source,
rank_no = excluded.rank_no,
crawl_time = excluded.crawl_time
""",
rows,
)
return len(rows)
# ---------------------------------------------------------------------------
# 命令行入口
# ---------------------------------------------------------------------------
def parse_args() -> argparse.Namespace:
"""解析命令行参数。"""
parser = argparse.ArgumentParser(description="爬取沪深 A 股行情并写入 SQLite")
parser.add_argument(
"--db",
type=Path,
default=DEFAULT_DB_PATH,
help=f"SQLite 数据库路径(默认:{DEFAULT_DB_PATH})",
)
parser.add_argument(
"--limit",
type=int,
default=100,
help="抓取的股票数量,默认 100",
)
parser.add_argument(
"--source",
choices=("auto", "eastmoney", "sina", "history"),
default="auto",
help=(
"数据源:auto 自动选择;eastmoney/sina 实时接口;"
"history 上一交易日日 K 线"
),
)
return parser.parse_args()
def format_number(value: Optional[float], digits: int = 2) -> str:
"""把可空数字格式化为字符串,方便在终端展示。"""
return "-" if value is None else f"{value:.{digits}f}"
def print_summary(records: List[StockRecord], source: str, db_path: Path) -> None:
"""打印抓取结果摘要。"""
print("-" * 92)
print(
f"{'排名':<4}{'代码':<8}{'名称':<12}{'最新价':>10}"
f"{'涨跌幅':>10}{'成交额(亿)':>12}{'PE':>9}{'PB':>8}"
)
for record in records[:10]:
amount_yi = record.amount / 100000000 if record.amount is not None else None
change_pct = (
f"{record.change_pct:.2f}%" if record.change_pct is not None else "-"
)
print(
f"{record.rank_no:<4}{record.code:<8}{record.name:<12}"
f"{format_number(record.price):>10}{change_pct:>10}"
f"{format_number(amount_yi):>12}{format_number(record.pe):>9}"
f"{format_number(record.pb):>8}"
)
print("-" * 92)
print(f"数据源:{source},共写入 {len(records)} 条")
print(f"数据库:{db_path.resolve()}")
def main() -> int:
"""程序主函数。"""
args = parse_args()
if args.limit <= 0:
print("--limit 必须为正整数", file=sys.stderr)
return 2
session = build_session()
args.db.parent.mkdir(parents=True, exist_ok=True)
conn = sqlite3.connect(args.db)
conn.row_factory = sqlite3.Row
init_db(conn)
try:
records, actual_source = fetch_records(session, args.limit, args.source)
if not records or not has_valid_quotes(records):
print(
"接口未返回有效报价,请稍后重试或使用 --source history",
file=sys.stderr,
)
return 1
count = save_records(conn, records)
print_summary(records, actual_source, args.db)
return 0 if count > 0 else 1
except (requests.RequestException, ValueError, json.JSONDecodeError) as exc:
print(f"抓取失败:{exc}", file=sys.stderr)
return 1
finally:
conn.close()
if __name__ == "__main__":
if hasattr(sys.stdout, "reconfigure"):
sys.stdout.reconfigure(encoding="utf-8")
if hasattr(sys.stderr, "reconfigure"):
sys.stderr.reconfigure(encoding="utf-8")
raise SystemExit(main())
运行结果
D:\flask_wangkeren\.venv\Scripts\python.exe D:\flask_wangkeren\102402104wkr\20261106\two.py
--------------------------------------------------------------------------------------------
排名 代码 名称 最新价 涨跌幅 成交额(亿) PE PB
1 300308 中际旭创 461.17 -6.52% 143.45 18.32 5.76
2 300502 新易盛 176.18 -5.08% 94.31 16.21 8.79
3 688825 长鑫科技 41.13 -3.29% 86.19 15.86 10.87
4 300750 宁德时代 255.17 -3.37% 85.58 13.72 3.05
5 002384 东山精密 82.37 -7.55% 75.32 22.72 6.08
6 300274 阳光电源 82.77 -2.78% 61.93 19.50 3.47
7 603986 兆易创新 246.88 -6.18% 56.38 11.78 2.26
8 002371 北方华创 567.20 1.10% 50.57 57.43 9.65
9 688256 寒武纪 825.68 -2.29% 50.33 104.84 34.33
10 688012 中微公司 260.60 2.60% 47.53 45.29 7.95
--------------------------------------------------------------------------------------------
数据源:eastmoney,共写入 100 条
数据库:D:\flask_wangkeren\102402104wkr\20261106\data\stock.db
Process finished with exit code 0

心得体会
股票作业最大的收获是“不要假设接口永远返回有效数据”。第一次运行时正好是盘前,东方财富返回的最新价全是 0;如果只看接口是否 200,就会把 0 写进数据库。two.py 用 has_valid_quotes 判断有效报价比例,再依次切换新浪和日 K 线接口,这种兜底思路比单纯加 try/except 更实用。
StockRecord 数据类让字段管理清晰很多。以前用字典,字段名拼错只有运行到入库时才发现;用 dataclass 之后,IDE 能补全,字段类型也一目了然。
成交量单位是一个典型的数据清洗问题:东方财富返回“手”,新浪返回“股”,日 K 线又不同。程序统一换算成“股”再入库,避免后续统计时数量级混乱。
作业3
爬取中国大学2021主榜( https://www.shanghairanking.cn/rankings/bcur/2021 )所有院校信息
完整代码
from future import annotations
import argparse
import json
import sqlite3
import sys
from datetime import datetime
from pathlib import Path
from typing import Any, Dict, List, Optional
import requests
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
BASE_DIR = Path(file).resolve().parent
DEFAULT_DB_PATH = BASE_DIR / "data" / "university.db"
API_URL = "https://www.shanghairanking.cn/api/pub/v1/bcur"
PAGE_URL = "https://www.shanghairanking.cn/rankings/bcur/2021"
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 build_session() -> requests.Session:
"""创建带重试机制的 requests 会话。"""
session = requests.Session()
retry = Retry(
total=3,
connect=3,
read=3,
backoff_factor=0.8,
status_forcelist=(429, 500, 502, 503, 504),
allowed_methods=frozenset({"GET"}),
)
adapter = HTTPAdapter(max_retries=retry)
session.mount("https://", adapter)
session.mount("http://", adapter)
session.headers.update(
{
"User-Agent": USER_AGENT,
"Accept": "application/json, text/plain, /",
"Accept-Language": "zh-CN,zh;q=0.9",
"Referer": PAGE_URL,
}
)
return session
def to_float(value: Any) -> Optional[float]:
if value is None:
return None
text = str(value).strip().replace(",", "")
if text in {"", "-", "--", "None", "null"}:
return None
try:
return float(text)
except ValueError:
return None
def fetch_rankings(session: requests.Session, year: int) -> List[Dict[str, Any]]:
params = {"bcur_type": "11", "year": str(year)}
response = session.get(API_URL, params=params, timeout=30)
response.raise_for_status()
try:
payload = response.json()
except json.JSONDecodeError as exc:
raise ValueError("软科接口返回的不是合法 JSON") from exc
if payload.get("code") != 200:
raise ValueError(f"软科接口返回错误:{payload.get('msg', '未知错误')}")
rankings = (payload.get("data") or {}).get("rankings") or []
if not rankings:
raise ValueError(f"{year} 年主榜没有返回院校数据")
return rankings
def parse_rankings(
rankings: List[Dict[str, Any]], year: int
) -> List[Dict[str, Any]]:
records: List[Dict[str, Any]] = []
for item in rankings:
name = str(item.get("univNameCn", "")).strip()
if not name:
continue
ranking_text = str(item.get("ranking", "")).strip()
try:
ranking = int(ranking_text)
except ValueError:
ranking = None
records.append(
{
"year": year,
"ranking": ranking,
"ranking_text": ranking_text,
"university_name": name,
"university_name_en": str(item.get("univNameEn", "")).strip(),
"province": str(item.get("province", "")).strip(),
"category": str(item.get("univCategory", "")).strip(),
"score": to_float(item.get("score")),
"tags": "、".join(item.get("univTags") or []),
}
)
return records
def init_db(conn: sqlite3.Connection) -> None:
conn.executescript(
"""
CREATE TABLE IF NOT EXISTS university_ranking (
id INTEGER PRIMARY KEY AUTOINCREMENT,
year INTEGER NOT NULL,
ranking INTEGER,
ranking_text TEXT,
university_name TEXT NOT NULL,
university_name_en TEXT,
province TEXT,
category TEXT,
score REAL,
tags TEXT,
crawl_time TEXT NOT NULL,
UNIQUE (year, university_name)
);
CREATE INDEX IF NOT EXISTS idx_university_rank
ON university_ranking (year, ranking);
CREATE INDEX IF NOT EXISTS idx_university_province
ON university_ranking (year, province);
"""
)
conn.commit()
def save_rankings(
conn: sqlite3.Connection, records: List[Dict[str, Any]]
) -> int:
now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
rows = [
(
record["year"],
record["ranking"],
record["ranking_text"],
record["university_name"],
record["university_name_en"],
record["province"],
record["category"],
record["score"],
record["tags"],
now,
)
for record in records
]
with conn:
conn.executemany(
"""
INSERT INTO university_ranking (
year, ranking, ranking_text, university_name,
university_name_en, province, category, score, tags, crawl_time
)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT (year, university_name) DO UPDATE SET
ranking = excluded.ranking,
ranking_text = excluded.ranking_text,
university_name_en = excluded.university_name_en,
province = excluded.province,
category = excluded.category,
score = excluded.score,
tags = excluded.tags,
crawl_time = excluded.crawl_time
""",
rows,
)
return len(rows)
def parse_args() -> argparse.Namespace:
"""解析命令行参数。"""
parser = argparse.ArgumentParser(description="爬取软科中国大学排名并写入 SQLite")
parser.add_argument(
"--year",
type=int,
default=2021,
help="排名年份,默认 2021",
)
parser.add_argument(
"--db",
type=Path,
default=DEFAULT_DB_PATH,
help=f"SQLite 数据库路径(默认:{DEFAULT_DB_PATH})",
)
return parser.parse_args()
def print_summary(
records: List[Dict[str, Any]], year: int, db_path: Path
) -> None:
categories: Dict[str, int] = {}
provinces: Dict[str, int] = {}
for record in records:
categories[record["category"]] = categories.get(record["category"], 0) + 1
provinces[record["province"]] = provinces.get(record["province"], 0) + 1
print("-" * 72)
print(f"{'排名':<6}{'学校':<18}{'省市':<8}{'类型':<8}{'总分':>8}")
for record in records[:10]:
print(
f"{record['ranking_text']:<6}{record['university_name']:<18}"
f"{record['province']:<8}{record['category']:<8}"
f"{record['score'] if record['score'] is not None else '-':>8}"
)
print("-" * 72)
print(f"{year} 年主榜共 {len(records)} 所院校")
print("类型分布:" + ",".join(f"{k} {v}" for k, v in sorted(categories.items())))
print(f"覆盖省市:{len(provinces)} 个")
print(f"数据库:{db_path.resolve()}")
def main() -> int:
"""程序主函数。"""
args = parse_args()
args.db.parent.mkdir(parents=True, exist_ok=True)
session = build_session()
conn = sqlite3.connect(args.db)
conn.row_factory = sqlite3.Row
init_db(conn)
try:
raw_rankings = fetch_rankings(session, args.year)
records = parse_rankings(raw_rankings, args.year)
count = save_rankings(conn, records)
print_summary(records, args.year, args.db)
return 0 if count > 0 else 1
except (requests.RequestException, ValueError, json.JSONDecodeError) as exc:
print(f"抓取失败:{exc}", file=sys.stderr)
return 1
finally:
conn.close()
if name == "main":
if hasattr(sys.stdout, "reconfigure"):
sys.stdout.reconfigure(encoding="utf-8")
if hasattr(sys.stderr, "reconfigure"):
sys.stderr.reconfigure(encoding="utf-8")
raise SystemExit(main())
运行结果
D:\flask_wangkeren\.venv\Scripts\python.exe D:\flask_wangkeren\102402104wkr\20261106\data\three.py
------------------------------------------------------------------------
排名 学校 省市 类型 总分
1 清华大学 北京 综合 969.2
2 北京大学 北京 综合 855.3
3 浙江大学 浙江 综合 768.7
4 上海交通大学 上海 综合 723.4
5 南京大学 江苏 综合 654.8
6 复旦大学 上海 综合 649.7
7 中国科学技术大学 安徽 理工 577.0
8 华中科技大学 湖北 综合 574.3
9 武汉大学 湖北 综合 567.9
10 西安交通大学 陕西 综合 537.9
------------------------------------------------------------------------
2021 年主榜共 582 所院校
类型分布:农业 34,师范 159,林业 6,理工 211,综合 172
覆盖省市:31 个
数据库:D:\flask_wangkeren\102402104wkr\20261106\data\data\university.db
Process finished with exit code 0

实验心得
大学排名作业让我体会到接口采集比 HTML 采集稳定:字段是结构化的,不需要猜 CSS 选择器。但接口也有坑,比如 ranking 是字符串、score 可能是 null、tags 是列表,必须逐项清洗。
SQLite 的 UPSERT 和唯一键在两次作业里都发挥了作用。重复运行不会产生重复数据,这比每次先 DELETE 再 INSERT 更安全,也更适合增量更新。
浙公网安备 33010602011771号