数据融合与采集技术作业三

一、实验内容与核心代码

1. 三项作业的实现过程

本次实验分为三个部分:使用单线程和多线程采集站点图片;使用 Scrapy 获取东方财富股票行情并写入 MySQL;使用 Scrapy 和 XPath 解析中国银行外汇牌价并写入 MySQL。

作业①:单线程与多线程采集图片

程序从中国气象网首页开始,广度优先访问同域名页面。程序根据学号末两位限制页面数,根据末三位限制去重图片 URL 数量。输入只在运行时保存在内存中,不会写入文件。下载阶段可选择单线程、多线程或两种模式都运行。

核心代码:

def collect_image_urls(max_pages: int, max_images: int) -> list[str]:
    """广度优先访问同站页面,并同时限制页面数和图片 URL 数。"""
    pending = [START_URL]
    visited = set()
    all_images = []
    seen_images = set()

    while pending and len(visited) < max_pages and len(all_images) < max_images:
        page_url = pending.pop(0)
        if page_url in visited or not is_site_page(page_url):
            continue
        visited.add(page_url)
        image_urls, page_links = page_image_and_links(page_url)

        # 用集合去重,并在追加前检查图片数量上限。
        for image_url in image_urls:
            if image_url not in seen_images and len(all_images) < max_images:
                seen_images.add(image_url)
                all_images.append(image_url)
        for next_url in page_links:
            if next_url not in visited and next_url not in pending:
                pending.append(next_url)
    return all_images


def download_images(image_urls: list[str], mode: str) -> None:
    """single 顺序下载;multi 使用线程池并发下载。"""
    tasks = [(index, url, IMAGE_ROOT / mode)
             for index, url in enumerate(image_urls, start=1)]
    if mode == "single":
        results = [download_one(task) for task in tasks]
    else:
        with ThreadPoolExecutor(max_workers=MAX_WORKERS) as executor:
            futures = [executor.submit(download_one, task) for task in tasks]
            results = [future.result() for future in as_completed(futures)]

    # 每张图片的 URL 和保存结果都会输出,方便核对采集过程。
    for image_url, status in results:
        print(f"图片 URL:{image_url}\n结果:{status}")

完整代码位于 作业1/1.py。页面解析使用 BeautifulSoup,线程池使用 ThreadPoolExecutor,文件以序号和 URL 哈希命名,避免同名图片互相覆盖。

image
image
image
image

image

作业②:东方财富股票行情入库

作业②通过 Scrapy 请求东方财富公开行情列表接口,解析 JSON 行情字段,再请求个股详情页面,用 XPath 提取名称。抓取结果封装为 StockItem,由 Pipeline 参数化写入 MySQL。默认抓取 50 条,可通过 .env 中的 STOCK_LIMIT 调整。

核心代码:

def parse_list(self, response, stock_limit):
    """解析 JSON 列表并把每只股票字段传给详情页回调。"""
    payload = json.loads(response.text)
    rows = ((payload.get("data") or {}).get("diff") or [])[:stock_limit]
    for raw in rows:
        code = str(raw.get("f12", "")).strip()
        if not code:
            continue
        row = {
            "stock_code": code,
            "stock_name": str(raw.get("f14", "")).strip(),
            "latest_price": number_or_none(raw.get("f2")),
            "change_percent": number_or_none(raw.get("f3")),
            "change_amount": number_or_none(raw.get("f4")),
            "volume": number_or_none(raw.get("f5")),
            "amplitude": number_or_none(raw.get("f7")),
            "high": number_or_none(raw.get("f15")),
            "low": number_or_none(raw.get("f16")),
            "open_price": number_or_none(raw.get("f17")),
            "previous_close": number_or_none(raw.get("f18")),
        }
        prefix = "sh" if code.startswith("6") else "bj" if code.startswith(("4", "8")) else "sz"
        detail_url = f"https://quote.eastmoney.com/{prefix}{code}.html"
        # 详情 HTML 中再用 XPath 解析股票名称。
        yield scrapy.Request(detail_url, callback=self.parse_detail,
                             meta={"stock_row": row}, dont_filter=True)


def parse_detail(self, response):
    """XPath 取个股名称,封装 Item 交给 Pipeline。"""
    row = response.meta["stock_row"]
    name = response.xpath(
        '//span[contains(@class, "quote_title_name")]/text()'
    ).get()
    if name and name.strip():
        row["stock_name"] = name.strip()
    yield StockItem(**row)

Pipeline 使用 SQL 参数占位符写入字段,并对重复股票代码执行更新。

image

image

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

外汇 Spider 访问中国银行外汇牌价页面,并限定 XPath 查询范围为 priceTable 表格。按列读取 Currency、TBP、CBP、TSP、CSP、日期和时间,将结果交给 ExchangeRateItem 与 Pipeline。

核心代码:

def parse(self, response):
    """从外汇表格每行提取货币、牌价和发布时间。"""
    rows = response.xpath('//*[@id="priceTable"]//tr[td]')
    for row in rows:
        cells = [
            " ".join(text.strip() for text in cell.xpath(".//text()").getall()
                      if text.strip())
            for cell in row.xpath("./td")
        ]
        # 表格前五列为货币和四种牌价;第七、八列为日期和时间。
        if len(cells) < 8 or not cells[0]:
            continue
        yield ExchangeRateItem(
            currency=cells[0],
            tbp=self.to_decimal(cells[1]),
            cbp=self.to_decimal(cells[2]),
            tsp=self.to_decimal(cells[3]),
            csp=self.to_decimal(cells[4]),
            quote_date=self.normalize_date(cells[6]),
            quote_time=self.normalize_time(cells[7]),
        )

数据库表额外保存报价日期,避免不同日期的相同货币报价被覆盖。重复采集相同货币和报价时间时,Pipeline 更新对应牌价。

image
image

2. 实验心得与运行说明

本次实验让我把网页请求、页面解析、并发下载和数据库存储串成了完整的数据采集流程。图片任务中,页面队列和集合分别用于控制访问范围、避免重复;多线程能够并发等待网络响应,但并发数仍需要限制。股票任务的数据列表采用 JSON,因此先解析接口字段,再用详情页 XPath 完成页面解析练习。外汇任务则直接用 XPath 定位表格行列,适合结构稳定的 HTML 表格。

运行前安装 requirements.txt 中的依赖,将 .env.example 复制为 .env 并填写本机 MySQL 密码,再执行 schema.sql 创建数据库。图片程序运行命令为 python .\作业1\1.py;股票项目进入 作业2 后执行 scrapy crawl stocks;外汇项目进入 作业3 后执行 scrapy crawl boc_exchange。数据库可以分别查询 eastmoney_stock 和 boc_exchange_rate。

二、提交材料与结果

1. 文件结构、数据库查询与提交链接

主要目录结构如下:

实验3/
├── 作业1/
│   ├── 1.py
│   └── images/
│       ├── single/
│       └── multi/
├── 作业2/
│   ├── scrapy.cfg
│   └── eastmoney_project/
├── 作业3/
│   ├── scrapy.cfg
│   └── boc_project/
├── .env.example
├── requirements.txt
├── schema.sql
└── README.md

数据库查询示例:

USE homework3;

-- 查询股票代码、名称、价格、涨跌和成交信息
SELECT stock_code, stock_name, latest_price, change_percent, change_amount,
       volume, amplitude, high_price, low_price, open_price, previous_close
FROM eastmoney_stock;

-- 查询中国银行外汇牌价
SELECT currency, tbp, cbp, tsp, csp, quote_date, quote_time
FROM boc_exchange_rate;

Gitee 作业文件夹:数据融合与采集技术作业三

2. 博客园截图与心得

通过本次实验,我更熟悉了 Scrapy 的 Spider、Item 和 Pipeline 的分工,也理解了 XPath 选择器必须结合页面实际结构编写。将数据库写入集中放在 Pipeline 后,Spider 只负责采集和清洗字段,程序结构更清楚。后续遇到网站结构或接口字段变化时,需要先查看实际响应,再调整解析路径和字段映射。

posted @ 2026-11-18 17:17  十月有什么呢  阅读(7)  评论(0)    收藏  举报