数据采集第3次作业

学号 102402138,按要求取学号后两位 38 作为翻页上限,后三位 138 作为图片下载上限。本次作业分三部分:爬中国气象网图片(单线程 / 多线程两个版本)、Scrapy 爬东方财富股票行情入库、Scrapy + XPath 爬中国银行外汇牌价入库。数据库用本机 MariaDB(MySQL 兼容),通过 pymysql 连接,库名 mydb。
| 代码git地址 | https://gitee.com/xun1342/2026shujucaijiyuronghejishuwzx/tree/master/作业3/ |


3-1 中国气象网图片爬虫

3-1.1 作业代码与运行结果

起始页用的是广州天气页面 http://www.weather.com.cn/weather/101280601.shtml,顺着页面里的 <a> 链接做广度优先遍历,碰到 <img> 就下载到本地目录。页面和图片地址都用 urljoin 把相对路径补成绝对地址,同时维护 visited、done 两个集合去重。两个计数器卡住规模:最多爬 38 个页面、最多下 138 张图,到数就停。

(1)单线程版本:imagespider_single.py

单线程下完一张图再请求下一张,顺序最稳定:

# -*- coding: utf-8 -*-
"""作业① 单线程爬取中国气象网图片(学号102402138:38页/138张)"""
import os, sys, urllib.request, urllib.parse
from bs4 import BeautifulSoup
from bs4 import UnicodeDammit

START_URL = "http://www.weather.com.cn/weather/101280601.shtml"
DOMAIN = "weather.com.cn"
MAX_PAGES = 38
MAX_IMAGES = 138
SAVE_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "images")

headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/120.0"}
visited, done, count = set(), set(), 0

def download(url):
    global count
    if count >= MAX_IMAGES: return
    try:
        ext = url[len(url)-4:] if url[len(url)-4] == "." else ".jpg"
        data = urllib.request.urlopen(
            urllib.request.Request(url, headers=headers), timeout=60).read()
        with open(os.path.join(SAVE_DIR, str(count+1)+ext), "wb") as f:
            f.write(data)
        count += 1; done.add(url)
        print("downloaded", count, "<-", url)
    except Exception as e:
        print("download error:", e, url)

def spider(start_url):
    queue = [start_url]
    while queue and len(visited) < MAX_PAGES:
        url = queue.pop(0)
        if url in visited: continue
        visited.add(url)
        print("="*50); print("page", len(visited), "/", MAX_PAGES, url)
        try:
            data = urllib.request.urlopen(
                urllib.request.Request(url, headers=headers), timeout=20).read()
            soup = BeautifulSoup(
                UnicodeDammit(data, ["utf-8","gbk"]).unicode_markup, "lxml")
            for img in soup.select("img"):
                if count >= MAX_IMAGES: break
                src = img.get("src")
                if not src: continue
                u = urllib.parse.urljoin(url, src)
                if u not in done:
                    print("  [img]", u); download(u)
            for a in soup.select("a"):
                h = a.get("href")
                if not h: continue
                pu = urllib.parse.urljoin(url, h)
                if DOMAIN in pu and pu not in visited: queue.append(pu)
        except Exception as e:
            print("page error:", e, url)

if __name__ == "__main__":
    os.makedirs(SAVE_DIR, exist_ok=True)
    print("单线程开始:", START_URL, "限制", MAX_PAGES, "页/", MAX_IMAGES, "张")
    spider(START_URL)
    print("The End 共爬页面 %d 下载图片 %d" % (len(visited), count))

单线程运行开始:

01_单线程-运行开始

单线程运行结束,共爬 38 页、下载 138 张:

02_单线程-运行结束

下载的图片存到 images 目录:

03_单线程-images目录

image

(2)多线程版本:imagespider_multithread.py

多线程版本前面采集 URL 的过程和单线程一样,区别在下载部分:发现一张图片就开一个子线程去下载,主线程继续解析下一个页面,最后 join() 等所有线程结束。共享的 count、done 用一把锁保护,避免多个线程同时改计数器导致重复计数。

# -*- coding: utf-8 -*-
"""作业① 多线程爬取中国气象网图片(学号102402138:38页/138张)"""
import os, threading, urllib.request, urllib.parse
from bs4 import BeautifulSoup
from bs4 import UnicodeDammit

START_URL = "http://www.weather.com.cn/weather/101280601.shtml"
DOMAIN = "weather.com.cn"
MAX_PAGES = 38
MAX_IMAGES = 138
SAVE_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "images_multi")
headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/120.0"}
visited, done, count, lock, threads = set(), set(), 0, threading.Lock(), []

def download(url, idx):
    try:
        ext = url[len(url)-4:] if url[len(url)-4] == "." else ".jpg"
        data = urllib.request.urlopen(
            urllib.request.Request(url, headers=headers), timeout=60).read()
        with open(os.path.join(SAVE_DIR, "m"+str(idx)+ext), "wb") as f:
            f.write(data)
        print("downloaded m%d" % idx, "<-", url)
    except Exception as e:
        print("download error:", e, url)

def spider(start_url):
    global count
    queue = [start_url]
    while queue and len(visited) < MAX_PAGES:
        url = queue.pop(0)
        if url in visited: continue
        visited.add(url)
        print("="*50); print("page", len(visited), "/", MAX_PAGES, url)
        try:
            data = urllib.request.urlopen(
                urllib.request.Request(url, headers=headers), timeout=20).read()
            soup = BeautifulSoup(
                UnicodeDammit(data, ["utf-8","gbk"]).unicode_markup, "lxml")
            for img in soup.select("img"):
                src = img.get("src")
                if not src: continue
                u = urllib.parse.urljoin(url, src)
                with lock:
                    if u in done or count >= MAX_IMAGES: continue
                    count += 1; idx = count; done.add(u)
                print("  [img]", u)
                t = threading.Thread(target=download, args=(u, idx))
                t.start(); threads.append(t)
            for a in soup.select("a"):
                h = a.get("href")
                if not h: continue
                pu = urllib.parse.urljoin(url, h)
                if DOMAIN in pu and pu not in visited: queue.append(pu)
        except Exception as e:
            print("page error:", e, url)

if __name__ == "__main__":
    os.makedirs(SAVE_DIR, exist_ok=True)
    print("多线程开始:", START_URL, "限制", MAX_PAGES, "页/", MAX_IMAGES, "张")
    spider(START_URL)
    for t in threads: t.join()
    print("The End 共爬页面 %d 下载图片 %d" % (len(visited), count))

多线程运行开始:

05_多线程-运行开始

多线程运行结束:

06_多线程-运行结束

图片存到 images_multi 目录,本次实际落盘 135 张(有 3 张请求超时或写入失败,多线程并发下比较常见):

07_多线程-images目录

image

3-1.2 作业心得

单线程版一开始我以为程序卡死了,其实是某张图下载慢,后面的请求全在排队等它。改成多线程之后明显快了,日志里图片下载是乱序完成的,不再严格按页面顺序来,这就是并发的效果。

一开始没加上限,爬虫顺着气象网的城市链接一路爬到别的城市去了,根本停不下来。用学号尾数当页数和图片数上限确实有必要,既控制了爬取规模,也不会把对方服务器压得太狠。

编码上踩了个坑。气象网页面编码不统一,直接 decode() 容易乱码,用 UnicodeDammit 按 utf-8、gbk 顺序自动识别就正常了。另外 <img src> 里很多是 /images/a.jpg 这种相对路径,必须 urljoin 补全成绝对地址,否则图片根本下不下来。多线程那边要注意共享变量:count 和 done 不加锁的话,两个线程同时读到同一个计数,会出现重复编号或者漏数。


3-2 东方财富股票行情(Scrapy + MySQL)

3-2.1 作业代码与运行结果

作业②爬东方财富沪深 A 股行情。行情中心页面是 JS 渲染的,直接请求拿到的是空壳页面,所以我直接用它的数据接口取 JSON,在 parse 里把每条记录映射成 Item,再交给 Pipeline 写 MySQL。字段对应作业要求的 12 个表头:序号、股票代码、股票名称、最新报价、涨跌幅、涨跌额、成交量、振幅、最高、最低、今开、昨收。

items.py 定义字段:

# -*- coding: utf-8 -*-
"""作业② StockItem 字段定义"""
import scrapy

class StockItem(scrapy.Item):
    id = scrapy.Field()
    bStockNo = scrapy.Field()
    bStockName = scrapy.Field()
    bNewPrice = scrapy.Field()
    bPctChg = scrapy.Field()
    bChg = scrapy.Field()
    bVolume = scrapy.Field()
    bAmplitude = scrapy.Field()
    bHigh = scrapy.Field()
    bLow = scrapy.Field()
    bOpen = scrapy.Field()
    bPreClose = scrapy.Field()

stock_spider.py 请求接口并解析 JSON:

# -*- coding: utf-8 -*-
"""作业②:stock_spider.py —— 东方财富沪深A股行情爬虫"""
import json
import scrapy
from stock.items import StockItem


class StockSpider(scrapy.Spider):
    name = "stockSpider"
    start_urls = [(
        "http://push2.eastmoney.com/api/qt/clist/get?"
        "pn=1&pz=50&po=1&np=1&fltt=2&invt=2&fid=f3"
        "&fs=m:0+t:6,m:0+t:80,m:1+t:2,m:1+t:23"
        "&fields=f12,f14,f2,f3,f4,f5,f6,f7,f15,f16,f17,f18"
    )]

    def parse(self, response):
        try:
            self.logger.info("收到响应: %s, 长度 %d", response.url, len(response.body))
            j = json.loads(response.body.decode("utf-8"))
            diff = j["data"]["diff"]
            self.logger.info("解析到 %d 只股票", len(diff))
            for i, s in enumerate(diff, 1):
                item = StockItem()
                item["id"] = str(i)
                item["bStockNo"] = str(s.get("f12", "") or "")     # 代码
                item["bStockName"] = str(s.get("f14", "") or "")  # 名称
                item["bNewPrice"] = str(s.get("f2", "") or "")     # 最新价
                item["bPctChg"] = str(s.get("f3", "") or "")       # 涨跌幅
                item["bChg"] = str(s.get("f4", "") or "")          # 涨跌额
                item["bVolume"] = str(s.get("f5", "") or "")       # 成交量
                item["bAmplitude"] = str(s.get("f7", "") or "")    # 振幅
                item["bHigh"] = str(s.get("f15", "") or "")         # 最高
                item["bLow"] = str(s.get("f16", "") or "")         # 最低
                item["bOpen"] = str(s.get("f17", "") or "")        # 今开
                item["bPreClose"] = str(s.get("f18", "") or "")    # 昨收
                if not item["bStockNo"]:
                    continue
                yield item
        except Exception as err:
            self.logger.error("parse error: %s", err)

    def errback(self, failure):
        self.logger.error(repr(failure))

pipelines.py 用 pymysql 连接数据库,open_spider 里建表,process_item 逐条插入,close_spider 提交并关闭连接。连接参数放在 settings.py 的 MYSQL_CONFIG 里,改密码不用动 Pipeline 代码:

# -*- coding: utf-8 -*-
"""作业② StockPipeline —— 把股票数据存入 MySQL"""
import pymysql


class StockPipeline(object):
    def open_spider(self, spider):
        cfg = spider.settings.get("MYSQL_CONFIG", {})
        try:
            self.con = pymysql.connect(
                host=cfg.get("host", "127.0.0.1"),
                port=cfg.get("port", 3306),
                user=cfg.get("user", "root"),
                passwd=cfg.get("password", "123456"),
                db=cfg.get("db", "mydb"),
                charset="utf8"
            )
            self.cur = self.con.cursor()
            self.cur.execute("DROP TABLE IF EXISTS stocks")
            self.cur.execute("""CREATE TABLE stocks (
                id INT PRIMARY KEY AUTO_INCREMENT,
                bStockNo VARCHAR(16), bStockName VARCHAR(64),
                bNewPrice VARCHAR(16), bPctChg VARCHAR(16), bChg VARCHAR(16),
                bVolume VARCHAR(32), bAmplitude VARCHAR(16),
                bHigh VARCHAR(16), bLow VARCHAR(16),
                bOpen VARCHAR(16), bPreClose VARCHAR(16)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8""")
            self.opened = True
            self.count = 0
            print("opened stock pipeline")
        except Exception as e:
            print("MySQL connect error:", e)
            self.opened = False

    def process_item(self, item, spider):
        if not self.opened:
            return item
        self.cur.execute(
            """INSERT INTO stocks
               (bStockNo,bStockName,bNewPrice,bPctChg,bChg,bVolume,bAmplitude,
                bHigh,bLow,bOpen,bPreClose)
               VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)""",
            (item["bStockNo"], item["bStockName"], item["bNewPrice"],
             item["bPctChg"], item["bChg"], item["bVolume"], item["bAmplitude"],
             item["bHigh"], item["bLow"], item["bOpen"], item["bPreClose"]))
        self.count += 1
        return item

    def close_spider(self, spider):
        if self.opened:
            self.con.commit()
            self.con.close()
            print("closed, 共写入", self.count, "条")

运行入口 run.py:

# -*- coding: utf-8 -*-
"""作业② 启动入口"""
from scrapy import cmdline
cmdline.execute("scrapy crawl stockSpider -s LOG_ENABLED=False".split())

Scrapy 运行结束,Pipeline 共写入 50 条股票:

09_股票-Scrapy运行

用 HeidiSQL 客户端连上 mydb,图形化查看同一张 stocks 表(10 行 × 12 列):

10_股票-MySQL数据表

数据库 stocks 表共 50 条记录,前 10 条如下:

10_股票-HeidiSQL数据表

3-2.2 作业心得

这次作业把 Scrapy 的 Item、Spider、Pipeline 三层真正走了一遍。Spider 只负责发请求、解析 JSON、yield Item,写库全交给 Pipeline,以后要换数据库只改 Pipeline 这一个文件就行,爬虫解析逻辑不用动。

东方财富这个接口折腾了一下。行情页面是 JS 渲染的,普通 Request 拿不到数据,F12 在网络面板里找到它背后的 clist JSON 接口,一个请求就返回结构化数据,连 XPath 都省了。接口字段是 f12、f14、f2 这种编号,需要对照页面表头一个个对应到中文含义,我是边看接口返回边核对页面上的列名才对上的。

连接数据库时一开始把连接参数写死在 Pipeline 里,后来挪到 settings.py 的 MYSQL_CONFIG,密码和库名集中管理。另外接口里个别字段可能是空值,取的时候用 s.get("f12", "") or "" 兜一下,避免 None 直接进数据库报错。


3-3 中国银行外汇牌价(Scrapy + XPath + MySQL)

3-3.1 作业代码与运行结果

作业③爬中国银行外汇牌价页面 https://www.boc.cn/sourcedb/whpj/,用 XPath 解析牌价表,字段为 Currency、TBP(现汇买入价)、CBP(现钞买入价)、TSP(现汇卖出价)、CSP(现钞卖出价)、Time(发布时间)。

items.py:

# -*- coding: utf-8 -*-
import scrapy

class ForexItem(scrapy.Item):
    Currency = scrapy.Field()
    TBP = scrapy.Field()
    CBP = scrapy.Field()
    TSP = scrapy.Field()
    CSP = scrapy.Field()
    Time = scrapy.Field()

forex_spider.py 用 XPath 定位 id="priceTable" 的表格,逐行取单元格:

# -*- coding: utf-8 -*-
"""作业③ 中国银行外汇牌价爬虫"""
import scrapy
from bs4 import UnicodeDammit
from forex.items import ForexItem

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

    def parse(self, response):
        try:
            dammit = UnicodeDammit(response.body, ["utf-8", "gbk"])
            selector = scrapy.Selector(text=dammit.unicode_markup)
            rows = selector.xpath("//table[@id='priceTable']//tr")
            self.logger.info("解析到 %d 行", len(rows))
            for row in rows:
                tds = row.xpath("./td")
                if len(tds) < 8:
                    continue
                def text(i):
                    t = tds[i].xpath("./text()").extract_first()
                    return (t or "").strip()
                item = ForexItem()
                item["Currency"] = text(0)
                item["TBP"] = text(1)
                item["CBP"] = text(2)
                item["TSP"] = text(3)
                item["CSP"] = text(4)
                item["Time"] = text(7)
                if not item["Currency"]:
                    continue
                yield item
        except Exception as err:
            self.logger.error("parse error: %s", err)

pipelines.py 写入 forex 表,结构和股票 Pipeline 一致:

# -*- coding: utf-8 -*-
"""作业③ ForexPipeline —— 把外汇牌价存入 MySQL"""
import pymysql


class ForexPipeline(object):
    def open_spider(self, spider):
        cfg = spider.settings.get("MYSQL_CONFIG", {})
        try:
            self.con = pymysql.connect(
                host=cfg.get("host", "127.0.0.1"),
                port=cfg.get("port", 3306),
                user=cfg.get("user", "root"),
                passwd=cfg.get("password", "123456"),
                db=cfg.get("db", "mydb"),
                charset="utf8"
            )
            self.cur = self.con.cursor()
            self.cur.execute("DROP TABLE IF EXISTS forex")
            self.cur.execute("""CREATE TABLE forex (
                id INT PRIMARY KEY AUTO_INCREMENT,
                Currency VARCHAR(64),
                TBP VARCHAR(16), CBP VARCHAR(16),
                TSP VARCHAR(16), CSP VARCHAR(16),
                Time VARCHAR(32)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8""")
            self.opened = True
            self.count = 0
            print("opened forex pipeline")
        except Exception as e:
            print("MySQL connect error:", e)
            self.opened = False

    def process_item(self, item, spider):
        if not self.opened:
            return item
        self.cur.execute(
            "INSERT INTO forex (Currency,TBP,CBP,TSP,CSP,Time) VALUES (%s,%s,%s,%s,%s,%s)",
            (item["Currency"], item["TBP"], item["CBP"],
             item["TSP"], item["CSP"], item["Time"]))
        self.count += 1
        return item

    def close_spider(self, spider):
        if self.opened:
            self.con.commit()
            self.con.close()
            print("closed, 共写入", self.count, "条")

Scrapy 运行结束,共写入 45 条牌价:

11_外汇-Scrapy运行

数据库 forex 表共 45 条记录,前 10 条如下:

12_外汇-HeidiSQL数据表

用 HeidiSQL 客户端图形化查看同一张 forex 表(10 行 × 7 列):

12_外汇-MySQL数据表

3-3.2 作业心得

这部分重点练的是 XPath。一开始照搬网上教程里的 tableList,一条数据都取不出来,加日志才发现页面里根本没这个 id。把页面 HTML 打出来看,真实的表格 id 是 priceTable,每行有 8 个 <td>,不是教程说的 7 个;其中第 7 列是完整日期时间,第 8 列(索引 7)才是 HH:MM:SS 的发布时间,列位置得对着真实页面核对。

编码也踩了坑。中行页面响应头写的编码和实际内容不一致,不显式按 UTF-8 解码的话,"阿联酋迪拉姆""澳大利亚元"这些货币名会变成乱码,这里用 UnicodeDammit 先识别再交给 Selector 就正常了。

另外注意到有些货币的现汇买入价、现汇卖出价是空的(页面本身就没给这个价),取值时按空字符串处理,不强行填 0。用固定列索引的方式虽然简单,但很依赖页面结构,以后银行页面加一列或少一列,索引就会错位;更稳妥的做法是根据表头文字动态定位列,当前页面结构稳定,先用索引实现。

整体跑下来,这次作业把 requests、BeautifulSoup、多线程、Scrapy、XPath、pymysql 串了一遍。爬虫不是请求成功就完事,编码、相对路径、空值、字段含义和单位、重复数据这些都要在代码里处理,实际写的时候出错的地方基本都在这些细节上。

posted @ 2026-11-19 12:34  迅1342  阅读(11)  评论(0)    收藏  举报