AIGC标识 数据采集作业三:图片单多线程与 Scrapy 股票、外汇入库

一、图片采集:单线程与多线程

1.1 作业代码与运行结果

姓名:梁洪睿;学号:102402129;博客园:youone。

学号末两位是 29,末三位是 129。程序限定 HTML 页面不超过 29、唯一候选图片 URL 不超过 129。本次访问 中国天气网及其图片频道

作业① Gitee 文件夹: 作业1。

安装与运行示例(在本作业根目录执行):

python -m venv .venv
.\.venv\Scripts\python.exe -m pip install -r requirements.txt
.\.venv\Scripts\python.exe 作业1/1.py --mode compare

首次运行发现清单,后续默认读取 manifest.json。--mode single、--mode multi 分别执行两种方式,--refresh 重新发现页面。--max-pages 只能取 1~29,--max-images 只能取 1~129。图片保存至 作业1/images/single、作业1/images/multi;crawl.log 保留下载 URL 和失败信息。

两种方式共用一次页面发现结果,以同一 URL 清单比较。单线程使用循环,多线程使用最多 4 个工作线程。每个线程有独立 Session;程序验证图片内容、限制单文件大小、设置超时和有限重试、遵守 robots,并按域名控制请求启动间隔。

关键代码摘自实际 1.py;完整入口、URL 规范化与请求策略见源码目录。

def discover(policy: RequestPolicy, page_limit: int, image_limit: int) -> dict:
    """顺序广度发现页面;只保存最多指定数量的去重图片 URL。"""
    pages_dir = ROOT / "raw" / "pages"
    pages_dir.mkdir(parents=True, exist_ok=True)
    pending = deque(SEEDS)
    queued = set(SEEDS)
    candidates: dict[str, dict] = {}
    pages = []
    while pending and len(pages) < page_limit and len(candidates) < image_limit:
        url = pending.popleft()
        if not policy.allowed(url):
            LOGGER.warning("ROBOTS_BLOCK page=%s", url)
            continue
        record = {"url": url, "index": len(pages) + 1, "time": now()}
        pages.append(record)  # 失败页面也占用页数预算,防止失败重试突破上限。
        LOGGER.info("PAGE %02d/%d %s", len(pages), page_limit, url)
        try:
            policy.wait(url)
            response = session().get(url, timeout=(5, 20), allow_redirects=False)
            record["status"] = response.status_code
            response.raise_for_status()
            if response.is_redirect:
                target = canonical(url, response.headers.get("Location", ""))
                if target and urlsplit(target).hostname in PAGE_HOSTS and target not in queued:
                    queued.add(target)
                    pending.appendleft(target)
                continue
            if "html" not in response.headers.get("Content-Type", "").lower():
                record["skip"] = "not HTML"
                continue
            if len(response.content) > MAX_BYTES:
                record["skip"] = "page exceeds 8 MiB"
                continue
            filename = f"page_{len(pages):02d}.html"
            (pages_dir / filename).write_bytes(response.content)
            record["file"] = "raw/pages/" + filename
            record["sha256"] = sha256(response.content).hexdigest()
            document = html.fromstring(response.content)
            sources = document.xpath(
                "//img/@src | //img/@data-src | //img/@data-original | //img/@data-lazy-src"
                " | //source/@src | //input[@type='image']/@src"
            )
            # srcset 的多个分辨率均是图片地址,也纳入 URL 去重集合。
            for srcset in document.xpath("//img/@srcset | //source/@srcset"):
                sources.extend(part.strip().split()[0] for part in srcset.split(",") if part.strip())
            for source in sources:
                image_url = canonical(url, source)
                if image_url and is_image_host(image_url) and image_url not in candidates:
                    candidates[image_url] = {"url": image_url, "page_url": url}
                    if len(candidates) >= image_limit:
                        break
            record["unique_images_so_far"] = len(candidates)
            links = []
            for href in document.xpath("//a/@href"):
                target = canonical(url, href)
                if not target or urlsplit(target).hostname not in PAGE_HOSTS:
                    continue
                if target in queued or urlsplit(target).query:
                    continue
                if not (urlsplit(target).path.endswith(("/", ".shtml", ".html"))):
                    continue
                links.append(target)
            # 图集页优先;仍只访问白名单站内页面。
            links.sort(key=lambda link: (urlsplit(link).hostname != "p.weather.com.cn", link.endswith("/")))
            for target in links:
                if target not in queued:
                    queued.add(target)
                    pending.append(target)
        except (requests.RequestException, ValueError) as exc:
            record["error"] = str(exc)
            LOGGER.warning("PAGE_FAILED %s %s", url, exc)
    manifest = {
        "student_id": STUDENT_ID, "student_name": "梁洪睿", "created_at": now(),
        "page_limit": page_limit, "image_limit": image_limit,
        "pages_requested": len(pages), "pages": pages, "images": list(candidates.values()),
        "robots": policy.robot_notes,
    }
    (ROOT / "manifest.json").write_text(json.dumps(manifest, ensure_ascii=False, indent=2), encoding="utf-8")
    archive_obsolete(pages_dir, {Path(page["file"]).name for page in pages if "file" in page}, "pages")
    return manifest


def download(entry: dict, mode: str, policy: RequestPolicy) -> dict:
    """下载并验证图片:成功后原子写入,失败不会生成占位图片。"""
    url = entry["url"]
    result = {**entry, "mode": mode, "started_at": now(), "ok": False}
    if not policy.allowed(url):
        result["error"] = "robots blocked"
        LOGGER.warning("ROBOTS_BLOCK image=%s", url)
        return result
    for attempt in range(1, 3):
        result["attempts"] = attempt
        LOGGER.info("DOWNLOAD mode=%s attempt=%d url=%s", mode, attempt, url)
        try:
            policy.wait(url)
            with session().get(url, timeout=(5, 20), stream=True, allow_redirects=False,
                               headers={"Referer": entry["page_url"]}) as response:
                response.raise_for_status()
                if response.is_redirect:
                    raise ValueError("redirect refused; destination not inspected")
                if int(response.headers.get("Content-Length", 0)) > MAX_BYTES:
                    raise ValueError("image exceeds 8 MiB")
                buffer = bytearray()
                for chunk in response.iter_content(65536):
                    buffer.extend(chunk)
                    if len(buffer) > MAX_BYTES:
                        raise ValueError("image exceeds 8 MiB")
                data = bytes(buffer)
                with Image.open(BytesIO(data)) as picture:
                    picture.verify()
                    image_format = picture.format or ""
                extension = {"JPEG": ".jpg", "PNG": ".png", "GIF": ".gif", "WEBP": ".webp", "BMP": ".bmp"}.get(image_format)
                if extension is None:
                    raise ValueError(f"unsupported image format {image_format}")
                name = sha256(url.encode("utf-8")).hexdigest()[:24] + extension
                destination = ROOT / "images" / mode / name
                temporary = destination.with_suffix(destination.suffix + ".part")
                temporary.write_bytes(data)
                temporary.replace(destination)
                result.update(ok=True, file=destination.relative_to(ROOT).as_posix(),
                              bytes=len(data), sha256=sha256(data).hexdigest(), format=image_format)
                LOGGER.info("SAVED mode=%s bytes=%d file=%s url=%s", mode, len(data), name, url)
                return result
        except (requests.RequestException, OSError, ValueError) as exc:
            result["error"] = str(exc)
            LOGGER.warning("DOWNLOAD_FAILED mode=%s url=%s error=%s", mode, url, exc)
            if isinstance(exc, requests.HTTPError) and exc.response is not None and 400 <= exc.response.status_code < 500:
                break  # 403/404 等永久性客户端错误不重试。
            if attempt < 2:
                time.sleep(0.4)
    return result


def run_mode(entries: list[dict], mode: str, workers: int, interval: float) -> dict:
    """单线程 for 循环与线程池 map 对同一份清单分别执行。"""
    output = ROOT / "images" / mode
    output.mkdir(parents=True, exist_ok=True)
    policy = RequestPolicy(interval)
    start = time.perf_counter()
    if mode == "single":
        records = [download(entry, mode, policy) for entry in entries]
    else:
        with ThreadPoolExecutor(max_workers=workers, thread_name_prefix="image") as executor:
            records = list(executor.map(lambda entry: download(entry, mode, policy), entries))
    result = {
        "mode": mode, "finished_at": now(), "workers": 1 if mode == "single" else workers,
        "elapsed_seconds": round(time.perf_counter() - start, 3),
        "planned": len(entries), "saved": sum(record["ok"] for record in records),
        "failed": sum(not record["ok"] for record in records),
        "robots": policy.robot_notes, "records": records,
    }
    (ROOT / f"result_{mode}.json").write_text(json.dumps(result, ensure_ascii=False, indent=2), encoding="utf-8")
    archive_obsolete(output, {Path(record["file"]).name for record in records if record["ok"]}, mode)
    LOGGER.info("RESULT mode=%s planned=%d saved=%d failed=%d elapsed=%.3fs", mode, result["planned"], result["saved"], result["failed"], result["elapsed_seconds"])
    return result

本次运行结束时间为 2026-11-14T11:13:49+08:00,实际访问 3 页,发现 129 个唯一候选 URL。

方式 线程数 计划下载 成功 失败 耗时/秒
单线程 1 129 127 2 17.287
多线程 4 129 127 2 12.474

两个模式分别下载相同候选,目录中有两个模式的结果副本;数量限制按每次方式和唯一 URL 清单统计。两模式成功 URL 集合一致:True,其中 127 份图片字节的 SHA-256 相同。本次耗时比为 1.386,只代表这次网络环境;缓存、服务器响应和限速都会影响结果。

下载失败数量如表所示;逐图片记录保留来源错误,未生成占位图片。实际成功数以表中数据为准。

实际图片采集统计、URL日志与下载图片展示

原始页面在 raw/pages,发现清单在 manifest.json,逐图片结果在 result_single.json、result_multi.json。独立核验重新读取图片字节、检查格式及 SHA-256,并核对清单和实际数量。

1.2 作业心得

有界采集首先要明确计数口径:访问页面数、候选 URL 数、成功保存数是不同的数字。图片链接存在也不代表图片一定可下载,所以成功与失败都需要保留,不能将 129 的上限直接当作下载成功数量。

并发主要改善网络等待,但也更容易让计数、共享 Session 和文件名产生冲突。本实现先生成去重后的有限清单,再向线程池提交任务;图片文件名由 URL 摘要生成,每个线程独立使用连接。这样可以直接检查提交任务是否超额,也能追踪每张图片的来源。

单次耗时不能说明线程数越多越快。本次比较保留相同输入和限速规则,同时记录失败数和图片摘要,才能判断两组结果是否具备可比性。

二、Scrapy 数据采集:股票与外汇

2.1 作业代码与运行结果

两项程序均采用 Scrapy → XPath/Item → ValidationPipeline → MySQLPipeline → SerializationPipeline。校验阶段将报价转为 Decimal,缺失值保留为 None;MySQL 阶段使用参数化 SQL,成功写入后才进入 JSON/CSV 导出。重复运行通过唯一键更新;数据库异常会留下错误并令启动器返回失败。

先按根目录 README 配置本机 MySQL,将连接参数写入 .env,再运行:

.\.venv\Scripts\python.exe 作业2/2.py
.\.venv\Scripts\python.exe 作业3/3.py
.\.venv\Scripts\python.exe verify_results.py

.env 中的口令不提交到仓库。JSON 为保证精度将 Decimal 导出为十进制字符串,数据库仍为 DECIMAL;CSV 使用 UTF-8 BOM,方便中文显示。

作业②:股票信息

作业② Gitee 文件夹: 作业2。

数据来源:东方财富个股HTML身份 + 腾讯证券公开行情响应。东方财富列表行情接口在本环境连接中断,因此本次采集 东方财富个股 HTML中的身份字段,再由 腾讯公开行情响应补全报价。完整来源地址保留在每条结果和原始响应清单中。

本次共获得 11 个来源响应,其中 10 个 HTML 页面用于 XPath 身份提取,实际入库 10 条,运行完成时间 2026-11-14T11:22:37.319190+08:00。行情是采集时来源返回的值,quote_time 为来源行情时间,collected_at 为本次采集时间,两者分开保存。

实现说明:真实HTML用XPath定位代码名称,再用腾讯公开行情响应补齐报价。 XPath 的具体任务是读取 normalize-space(//title) 并解析股票代码和名称;报价字段来自腾讯的 GB18030 编码、波浪线分隔响应。程序核对两个来源的代码及名称,并验证振幅与最高、最低、昨收的关系。这里的 12 列并非全部从 HTML 表格用 XPath 直接读取。

Item 与字段设计如下:股票代码使用字符串保留前导零,价格、涨跌额和百分比采用 DECIMAL,成交量单位为手,百分比字段中的 1.23 表示 1.23%。题目示例存在排版错位,程序按字段含义映射真实数据。

"""股票 Item,前12字段对应作业表格,额外字段用于溯源。"""
import scrapy


class StockItem(scrapy.Item):
    id = scrapy.Field()
    bStockNo = scrapy.Field()  # CHAR(6) 保留前导零。
    bStockName = scrapy.Field()
    latest_price = scrapy.Field()
    change_percent = scrapy.Field()  # 百分数值,2.37表示2.37%。
    change_amount = scrapy.Field()
    volume = scrapy.Field()  # 腾讯A股接口原始整数,单位手(100股)。
    amplitude = scrapy.Field()  # 百分数值。
    high_price = scrapy.Field()
    low_price = scrapy.Field()
    open_price = scrapy.Field()
    previous_close = scrapy.Field()
    volume_raw = scrapy.Field()
    quote_time = scrapy.Field()
    collected_at = scrapy.Field()
    source_url = scrapy.Field()  # 东方财富个股HTML。
    quote_source_url = scrapy.Field()  # 腾讯原始行情响应。
    source_page = scrapy.Field()
CREATE TABLE IF NOT EXISTS stocks (
    id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
    bStockNo CHAR(6) NOT NULL,
    bStockName VARCHAR(64) NOT NULL,
    latest_price DECIMAL(18,4) NULL,
    change_percent DECIMAL(12,4) NULL COMMENT '百分数值',
    change_amount DECIMAL(18,4) NULL,
    volume BIGINT UNSIGNED NULL COMMENT '手,一手=100股',
    amplitude DECIMAL(12,4) NULL COMMENT '百分数值',
    high_price DECIMAL(18,4) NULL,
    low_price DECIMAL(18,4) NULL,
    open_price DECIMAL(18,4) NULL,
    previous_close DECIMAL(18,4) NULL,
    volume_raw VARCHAR(32) NULL,
    quote_time DATETIME NOT NULL,
    collected_at DATETIME NOT NULL,
    source_url VARCHAR(512) NOT NULL,
    quote_source_url VARCHAR(1024) NOT NULL,
    source_page SMALLINT UNSIGNED NOT NULL,
    UNIQUE KEY uq_stock_code (bStockNo)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

Spider 的实际代码:

"""真实HTML用XPath定位代码名称,再用腾讯公开行情响应补齐报价。"""
import hashlib
import json
import re
import unicodedata
from datetime import datetime
from decimal import Decimal
from zoneinfo import ZoneInfo

import scrapy

from stockcollector.items import StockItem


class StocksSpider(scrapy.Spider):
    name = "stocks"
    allowed_domains = ["quote.eastmoney.com", "qt.gtimg.cn"]
    symbols = (
        "sz000001", "sh600000", "sh600519", "sz000002", "sz000063",
        "sz000333", "sz000651", "sz002594", "sh601318", "sh601398",
    )

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.identities = {}
        self.manifest = []
        self.collected_at = datetime.now(ZoneInfo("Asia/Shanghai")).replace(tzinfo=None, microsecond=0)

    def start_requests(self):
        for page_number, symbol in enumerate(self.symbols, 1):
            url = f"https://quote.eastmoney.com/{symbol}.html"
            yield scrapy.Request(url, callback=self.parse_identity, cb_kwargs={"symbol": symbol, "page_number": page_number})

    def save_raw(self, response, filename, parser):
        raw_dir = self.settings["BASE_DIR"] / "raw"
        raw_dir.mkdir(exist_ok=True)
        (raw_dir / filename).write_bytes(response.body)
        self.manifest.append({
            "url": response.url, "path": f"raw/{filename}", "status": response.status,
            "sha256": hashlib.sha256(response.body).hexdigest(), "parser": parser,
            "captured_at": datetime.now(ZoneInfo("Asia/Shanghai")).isoformat(),
        })
        (raw_dir / "manifest.json").write_text(json.dumps(self.manifest, ensure_ascii=False, indent=2), encoding="utf-8")

    def parse_identity(self, response, symbol, page_number):
        self.save_raw(response, f"identity_{symbol}.html", "XPath //title/text()")
        title = response.xpath("normalize-space(//title)").get()
        match = re.search(r"^(.+?)\((\d{6})\)", title or "")
        if not match or match.group(2) != symbol[2:]:
            raise ValueError(f"真实页面title未提供预期股票代码:{symbol} {title!r}")
        name, code = match.group(1).strip(), match.group(2)
        self.identities[code] = {"name": name, "url": response.url, "page_number": page_number}
        if len(self.identities) == len(self.symbols):
            quote_url = "https://qt.gtimg.cn/q=" + ",".join(self.symbols)
            yield scrapy.Request(quote_url, callback=self.parse_quotes)

    def parse_quotes(self, response):
        self.save_raw(response, "quotes.txt", "GB18030 + tilde-delimited vendor quote fields")
        text = response.body.decode("gb18030")
        quotes = {}
        for symbol, body in re.findall(r'v_(\w+)="(.*?)";', text):
            fields = body.split("~")
            if len(fields) < 44:
                raise ValueError(f"腾讯行情字段数量改变:{symbol}")
            quotes[symbol] = fields
        if set(quotes) != set(self.symbols):
            raise ValueError("行情响应缺少部分股票,禁止用默认值补齐")
        items = []
        for symbol in self.symbols:
            values = quotes[symbol]
            code = values[2]
            identity = self.identities[code]
            # 股票简称含排版空格/全角A;只规范这些等价字符,保留HTML原名。
            quote_name = re.sub(r"\s+", "", unicodedata.normalize("NFKC", values[1]))
            html_name = re.sub(r"\s+", "", unicodedata.normalize("NFKC", identity["name"]))
            if quote_name != html_name:
                raise ValueError(f"两来源名称不一致:{code} {identity['name']!r} {values[1]!r}")
            # 对关键字段作关系校验,防止接口列顺序发生变化后静默入库。
            previous = Decimal(values[4])
            expected_amplitude = (Decimal(values[33]) - Decimal(values[34])) / previous * 100
            if abs(expected_amplitude - Decimal(values[43])) > Decimal("0.02"):
                raise ValueError(f"振幅与最高/最低/昨收不一致:{code}")
            items.append(StockItem(
                bStockNo=code, bStockName=identity["name"], latest_price=values[3],
                change_percent=values[32], change_amount=values[31], volume=values[6],
                amplitude=values[43], high_price=values[33], low_price=values[34],
                open_price=values[5], previous_close=values[4], volume_raw=values[6],
                quote_time=datetime.strptime(values[30], "%Y%m%d%H%M%S"),
                collected_at=self.collected_at, source_url=identity["url"],
                quote_source_url=response.url, source_page=identity["page_number"],
            ))
        self.crawler.stats.set_value("source_pages", len(self.identities) + 1)
        self.crawler.stats.set_value("xpath_identity_pages", len(self.identities))
        # 整批验证通过后才交给 Pipeline,字段变化时不会导出半批记录。
        yield from items

下列片段分别展示数值校验、实际写入和序列化。连接配置、建表、Exporter 初始化等完整代码保存在 stockcollector/pipelines.py。

def process_item(self, item, spider):
    adapter = ItemAdapter(item)
    for field in self.settings["DECIMAL_FIELDS"]:
        value = adapter.get(field)
        if value is None or str(value).strip() in {"", "-", "--", "—"}:
            adapter[field] = None
            continue
        try:
            adapter[field] = Decimal(str(value).replace(",", "").replace("%", ""))
        except InvalidOperation as exc:
            raise ValueError(f"字段 {field} 无法转为数值:{value!r}") from exc
    return item


def process_item(self, item, spider):
    adapter = ItemAdapter(item)
    values = [adapter.get(field) for field in self.settings["DB_FIELDS"]]
    try:
        with self.connection.cursor() as cursor:
            cursor.execute(self.sql, values)
            adapter["id"] = cursor.lastrowid
        self.connection.commit()
    except pymysql.MySQLError:
        self.connection.rollback()
        self.crawler.stats.inc_value("mysql/errors")
        self.crawler.engine.close_spider(spider, reason="database_error")
        spider.logger.exception("MySQL 写入失败,本次运行判定失败")
        raise DropItem("MySQL写入失败,未导出此记录")
    self.crawler.stats.inc_value("mysql/inserted_count")
    return item


def process_item(self, item, spider):
    # JSON 用十进制字符串保证精度,MySQL 仍使用 DECIMAL 类型。
    row = {}
    for key, value in ItemAdapter(item).items():
        if isinstance(value, Decimal):
            value = format(value, "f")
        elif isinstance(value, datetime):
            value = value.isoformat(sep=" ")
        elif isinstance(value, timedelta):
            value = str(value)
        row[key] = value
    self.json_exporter.export_item(row)
    self.csv_exporter.export_item(row)
    print(" | ".join(str(row.get(field, "")) for field in self.settings["EXPORT_FIELDS"][:12]))
    return item

结果节选(完整数据见 output/stocks.json、stocks.csv):

序号 股票代码 股票名称 最新报价 涨跌幅/% 涨跌额 成交量/手 振幅/% 最高 最低 今开 昨收
1 000001 平安银行 12.07 2.37 0.28 2189430 3.39 12.10 11.70 11.76 11.79
2 600000 浦发银行 10.40 1.86 0.19 761573 3.13 10.44 10.12 10.19 10.21
3 600519 贵州茅台 1435.26 1.77 24.99 41780 3.10 1437.69 1394.00 1404.00 1410.27
7 000002 万 科A 3.06 -2.55 -0.08 1675267 2.87 3.15 3.06 3.15 3.14
8 000063 中兴通讯 28.06 0.11 0.03 601374 2.53 28.66 27.95 28.10 28.03

数据库真实查询结果展示:

股票 MySQL 实际查询结果

作业③:中国银行外汇牌价

作业③ Gitee 文件夹: 作业3。

来源为 中国银行外汇牌价,本次请求 1 页、入库 45 条,运行完成时间 2026-11-14T11:16:30.464738+08:00。原始表格含八列,输出使用如下映射,数据库额外保存发布日期与采集时间。

输出字段 来源字段
Currency 货币名称
TBP 现汇买入价
CBP 现钞买入价
TSP 现汇卖出价
CSP 现钞卖出价
Time 发布时间

四种牌价按来源为每 100 外币折合人民币的报价。部分币种缺少某种报价,本次四个价格字段合计 34 个 NULL,没有使用 0 填补。published_at 将发布日期与时间合并,避免不同日期的同一时刻发生冲突。

"""定义 Item;保留原页面的空缺报价和完整发布时间。"""
import scrapy


class ForexItem(scrapy.Item):
    id = scrapy.Field()
    Currency = scrapy.Field()
    TBP = scrapy.Field()  # Telegraphic buying price:现汇买入价。
    CBP = scrapy.Field()  # Cash buying price:现钞买入价。
    TSP = scrapy.Field()  # Telegraphic selling price:现汇卖出价。
    CSP = scrapy.Field()  # Cash selling price:现钞卖出价。
    Time = scrapy.Field()  # 按作业要求显示 HH:MM:SS。
    published_at = scrapy.Field()  # 数据库使用日期+时间,避免跨日冲突。
    collected_at = scrapy.Field()
    source_url = scrapy.Field()
"""只请求中行外汇牌价首页,用 XPath 直接读取真实 HTML。"""
from datetime import datetime
from zoneinfo import ZoneInfo

import scrapy

from fxcollector.items import ForexItem


class ForexSpider(scrapy.Spider):
    name = "forex"
    allowed_domains = ["boc.cn"]
    start_urls = ["https://www.boc.cn/sourcedb/whpj/"]

    def parse(self, response):
        raw_dir = self.settings["BASE_DIR"] / "raw"
        raw_dir.mkdir(exist_ok=True)
        (raw_dir / "source_001.html").write_bytes(response.body)
        rows = response.xpath('//table[@id="priceTable"]//tr[td]')
        if not rows:
            raise ValueError("中行牌价表未找到:请检查 HTML 结构,禁止生成示例数据。")
        collected_at = datetime.now(ZoneInfo("Asia/Shanghai")).replace(tzinfo=None, microsecond=0)
        seen = set()
        for row in rows:
            cells = [td.xpath("normalize-space(.)").get() for td in row.xpath("./td")]
            if len(cells) != 8:
                raise ValueError(f"牌价表列数改变,预期8列,实际{len(cells)}列")
            currency, tbp, cbp, tsp, csp, _, date_text, time_text = cells
            # 当前网页“发布日期”已经含时间;旧版只含日期,两种均兼容。
            published_at = datetime.strptime(date_text[:10] + " " + time_text, "%Y/%m/%d %H:%M:%S")
            key = (currency, published_at)
            if key in seen:
                continue
            seen.add(key)
            yield ForexItem(
                Currency=currency, TBP=tbp, CBP=cbp, TSP=tsp, CSP=csp,
                Time=time_text, published_at=published_at,
                collected_at=collected_at, source_url=response.url,
            )
        self.crawler.stats.set_value("source_pages", 1)

外汇校验同样保留空值并转换 Decimal:

def process_item(self, item, spider):
    adapter = ItemAdapter(item)
    for field in self.settings["DECIMAL_FIELDS"]:
        value = adapter.get(field)
        if value is None or str(value).strip() in {"", "-", "--", "—"}:
            adapter[field] = None
            continue
        try:
            adapter[field] = Decimal(str(value).replace(",", "").replace("%", ""))
        except InvalidOperation as exc:
            raise ValueError(f"字段 {field} 无法转为数值:{value!r}") from exc
    return item

MySQL 与序列化执行方式同上,字段配置为外汇字段。完整 Pipeline 在作业③目录;建表语句如下:

CREATE TABLE IF NOT EXISTS forex_quotes (
    id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
    Currency VARCHAR(64) NOT NULL,
    TBP DECIMAL(18,4) NULL COMMENT '现汇买入价,每100外币折合人民币',
    CBP DECIMAL(18,4) NULL COMMENT '现钞买入价,每100外币折合人民币',
    TSP DECIMAL(18,4) NULL COMMENT '现汇卖出价,每100外币折合人民币',
    CSP DECIMAL(18,4) NULL COMMENT '现钞卖出价,每100外币折合人民币',
    Time TIME NOT NULL,
    published_at DATETIME NOT NULL,
    collected_at DATETIME NOT NULL,
    source_url VARCHAR(512) NOT NULL,
    UNIQUE KEY uq_currency_time (Currency, published_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

六列结果节选:

Currency TBP CBP TSP CSP Time
阿联酋迪拉姆 180.4 180.4 182.94 182.94 10:30:00
澳大利亚元 450.69 450.69 454.27 454.27 10:30:00
文莱元 NULL 476.62 NULL 559.52 10:30:00
巴西雷亚尔 NULL 112.1 NULL 124.95 10:30:00
加拿大元 466.23 466.23 469.89 469.89 10:30:00
瑞士法郎 792.37 792.37 798.49 798.49 10:30:00
捷克克朗 NULL 26.82 NULL 33.46 10:30:00
丹麦克朗 98.03 98.03 98.81 98.81 10:30:00

中国银行外汇牌价 MySQL 实际查询结果

本次独立核验完成于 2026-11-14T11:24:30+08:00,48/48 项检查通过;MySQL 是否实查为 True,总体验证结果为 True。核验包含 JSON/CSV 一致、数据库记录匹配、外汇原始 HTML 字段对应、图片字节与格式、两模式相同输入等。详细报告见 verification.json。

2.2 作业心得

Item 让字段含义集中可查,Pipeline 将解析、校验、入库和导出分开。本实现中“导出成功”依赖“数据库写入成功”,因此 JSON/CSV 不会把未写入的数据混入成功结果。启动器仍会检查计数和错误状态,避免文件存在就误判整个运行成功。

XPath 能定位真实 HTML 节点,但遇到动态行情时,还要根据页面与数据结构说明实际取值过程。保留原始响应和来源地址,比只保留最终数字更容易复查列错位、结构变化和字段单位问题。

金额和报价使用 Decimal/DECIMAL,NULL 表示来源缺失,0 表示真实数值为零,两者不能混用。股票代码不是数学数值,应保留前导零;外汇发布时间必须配合日期存储。数据库唯一键与重复运行策略也需要与业务含义一致。

完整源代码、原始响应、MySQL 查询结果及独立核验报告保存在上述 Gitee 作业目录,便于复现和核对。

posted @ 2026-11-14 12:46  由一  阅读(7)  评论(0)    收藏  举报