数据采集第三次作业
作业①:网站图片批量爬取(单线程与多线程实现)
1)代码
import requests
from bs4 import BeautifulSoup
import os
import threading
import time
from urllib.parse import urljoin
# ========== 配置项 ==========
# 浏览器请求头,避免被网站拦截
HEADERS = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
"Accept-Language": "zh-CN,zh;q=0.9"
}
# 23个城市对应23个页面(匹配学号尾号23)
CITIES = {
"北京": "101010100", "上海": "101020100", "广州": "101280101",
"福州": "101230101", "成都": "101270101", "深圳": "101280601",
"杭州": "101210101", "南京": "101190101", "武汉": "101200101",
"西安": "101110101", "重庆": "101040100", "天津": "101030100",
"苏州": "101190401", "长沙": "101250101", "郑州": "101180101",
"青岛": "101120201", "大连": "101070201", "厦门": "101230201",
"昆明": "101290101", "哈尔滨": "101050101", "长春": "101060101",
"沈阳": "101070101", "济南": "101120101"
}
BASE_URL = "http://www.weather.com.cn/weather/{}.shtml"
SAVE_DIR = "images" # 图片保存目录
MAX_IMG_COUNT = 123 # 最大图片数量(匹配学号后三位123)
MAX_PAGE = 23 # 最大页面数
# 全局计数器与锁(多线程安全)
img_count = 0
count_lock = threading.Lock()
downloaded_urls = set() # URL去重集合
# ========== 工具函数 ==========
def init_dir():
"""初始化保存目录,不存在则创建"""
if not os.path.exists(SAVE_DIR):
os.mkdir(SAVE_DIR)
def get_page_img_urls(page_url):
"""获取单个页面的所有图片URL,返回去重后的列表"""
img_urls = []
try:
resp = requests.get(page_url, headers=HEADERS, timeout=10)
resp.encoding = "utf-8"
soup = BeautifulSoup(resp.text, "html.parser")
# 提取所有img标签的src属性
for img in soup.find_all("img"):
src = img.get("src")
if not src:
continue
# 相对路径转绝对路径
full_url = urljoin(page_url, src)
# 只保留常见图片格式
if full_url.endswith((".jpg", ".png", ".gif", ".jpeg", ".webp")):
img_urls.append(full_url)
return list(set(img_urls)) # 单页内去重
except Exception as e:
print(f" 页面请求失败 {page_url}: {e}")
return []
def download_single_img(img_url):
"""下载单张图片,自动按序号命名"""
global img_count
# 线程安全计数与上限控制
with count_lock:
if img_count >= MAX_IMG_COUNT or img_url in downloaded_urls:
return False
current_num = img_count + 1
img_count = current_num
downloaded_urls.add(img_url)
# 提取图片后缀
ext = os.path.splitext(img_url)[1]
if len(ext) > 5:
ext = ".jpg"
save_name = f"img_{current_num:03d}{ext}"
save_path = os.path.join(SAVE_DIR, save_name)
try:
resp = requests.get(img_url, headers=HEADERS, timeout=10)
with open(save_path, "wb") as f:
f.write(resp.content)
print(f" [下载成功] {img_url}")
return True
except Exception as e:
print(f" [下载失败] {img_url} 原因:{e}")
return False
# ========== 单线程爬取 ==========
def single_thread_crawl():
global img_count, downloaded_urls
# 重置状态
img_count = 0
downloaded_urls.clear()
init_dir()
print("\n" + "="*60)
print("【单线程模式】开始爬取")
print("="*60)
start_time = time.time()
page_num = 0
for city_name, city_code in CITIES.items():
if page_num >= MAX_PAGE or img_count >= MAX_IMG_COUNT:
break
page_num += 1
page_url = BASE_URL.format(city_code)
print(f"\n正在爬取第 {page_num} 页:{city_name}")
img_urls = get_page_img_urls(page_url)
print(f" 本页找到 {len(img_urls)} 张图片")
for img_url in img_urls:
if img_count >= MAX_IMG_COUNT:
break
download_single_img(img_url)
cost_time = round(time.time() - start_time, 2)
print("\n" + "="*60)
print(f"【单线程模式】爬取完成")
print(f" 总页面数:{page_num} 总图片数:{img_count} 总耗时:{cost_time} 秒")
print("="*60)
# ========== 多线程爬取 ==========
def multi_thread_crawl(thread_num=5):
global img_count, downloaded_urls
# 重置状态
img_count = 0
downloaded_urls.clear()
init_dir()
print("\n" + "="*60)
print(f"【多线程模式】开始爬取(线程数:{thread_num})")
print("="*60)
start_time = time.time()
# 第一步:单线程收集所有图片URL(页面请求串行,图片下载并发)
all_img_urls = []
page_num = 0
for city_name, city_code in CITIES.items():
if page_num >= MAX_PAGE:
break
page_num += 1
page_url = BASE_URL.format(city_code)
print(f"\n正在收集第 {page_num} 页图片URL:{city_name}")
img_urls = get_page_img_urls(page_url)
all_img_urls.extend(img_urls)
# 全局去重
all_img_urls = list(set(all_img_urls))
print(f"\n共收集到 {len(all_img_urls)} 张图片URL,开始多线程下载")
# 第二步:多线程并发下载
threads = []
def download_worker(url_list):
for url in url_list:
if img_count >= MAX_IMG_COUNT:
break
download_single_img(url)
# 平分URL给各个线程
per_thread = len(all_img_urls) // thread_num
for i in range(thread_num):
start = i * per_thread
end = start + per_thread if i != thread_num-1 else len(all_img_urls)
t = threading.Thread(target=download_worker, args=(all_img_urls[start:end],))
threads.append(t)
t.start()
# 等待所有线程结束
for t in threads:
t.join()
cost_time = round(time.time() - start_time, 2)
print("\n" + "="*60)
print(f"【多线程模式】爬取完成")
print(f" 总页面数:{page_num} 总图片数:{img_count} 总耗时:{cost_time} 秒")
print("="*60)
# ========== 主程序入口 ==========
if __name__ == "__main__":
# 先运行单线程
single_thread_crawl()
# 清空目录,再运行多线程(保证对比公平)
for file in os.listdir(SAVE_DIR):
os.remove(os.path.join(SAVE_DIR, file))
# 运行多线程(5线程)
multi_thread_crawl(thread_num=5)
实验结果:
成功将图片下载至本地 images 文件夹,控制台完整输出所有下载图片的 URL 信息


2)心得体会
通过本次图片爬取实验,我掌握了网页图片资源的提取、路径补全与本地存储的完整方法,也直观感受到了单线程与多线程爬虫的性能差异。实验中遇到了相对路径、省略协议路径等多种图片 URL 格式,通过拼接补全逐一解决,也让我体会到网页资源路径的多样性与处理技巧。
作业②:Scrapy 框架股票信息爬取
1)代码
数据模型items.py
import scrapy
class StockScrapyItem(scrapy.Item):
bStockNo = scrapy.Field() # 股票代码
bStockName = scrapy.Field() # 股票名称
bNewPrice = scrapy.Field() # 最新报价
bChangePercent = scrapy.Field() # 涨跌幅
bChangeAmount = scrapy.Field() # 涨跌额
bVolume = scrapy.Field() # 成交量
bAmplitude = scrapy.Field() # 振幅
bHigh = scrapy.Field() # 最高
bLow = scrapy.Field() # 最低
bOpen = scrapy.Field() # 今开
bPreClose = scrapy.Field() # 昨收
爬虫主程序 stock_spider.py
import scrapy
from stock_scrapy.items import StockScrapyItem
class StockSpider(scrapy.Spider):
name = "stock_spider"
allowed_domains = ["hq.sinajs.cn", "finance.sina.com.cn"]
start_urls = [
" https://hq.sinajs.cn/list=sh688093 ,sh600519,sz000001,sz300750,sh601318"
]
def parse(self, response):
text = response.body.decode("gbk")
lines = text.strip().split("\n")
stock_codes = ["sh688093", "sh600519", "sz000001", "sz300750", "sh601318"]
for code, line in zip(stock_codes, lines):
content = line.split('"')[1]
fields = content.split(",")
if len(fields) < 32:
continue
item = StockScrapyItem()
item["bStockNo"] = code[2:]
item["bStockName"] = fields[0]
item["bOpen"] = float(fields[1])
item["bPreClose"] = float(fields[2])
item["bNewPrice"] = float(fields[3])
item["bHigh"] = float(fields[4])
item["bLow"] = float(fields[5])
item["bVolume"] = int(float(fields[8]))
item["bChangeAmount"] = round(float(fields[3]) - float(fields[2]), 2)
item["bChangePercent"] = round((float(fields[3]) - float(fields[2])) / float(fields[2]) * 100, 2)
item["bAmplitude"] = round((float(fields[4]) - float(fields[5])) / float(fields[2]) * 100, 2)
yield item
数据管道 pipelines.py
import sqlite3
class StockSqlitePipeline:
def __init__(self):
self.db_path = "stock.db"
def open_spider(self, spider):
self.conn = sqlite3.connect(self.db_path)
self.cursor = self.conn.cursor()
self.cursor.execute("""
CREATE TABLE IF NOT EXISTS stock_info (
id INTEGER PRIMARY KEY AUTOINCREMENT,
bStockNo TEXT,
bStockName TEXT,
bNewPrice REAL,
bChangePercent REAL,
bChangeAmount REAL,
bVolume INTEGER,
bAmplitude REAL,
bHigh REAL,
bLow REAL,
bOpen REAL,
bPreClose REAL
)
""")
self.conn.commit()
def process_item(self, item, spider):
self.cursor.execute("""
INSERT INTO stock_info
(bStockNo, bStockName, bNewPrice, bChangePercent, bChangeAmount, bVolume, bAmplitude, bHigh, bLow, bOpen, bPreClose)
VALUES (?,?,?,?,?,?,?,?,?,?,?)
""", (
item["bStockNo"], item["bStockName"], item["bNewPrice"],
item["bChangePercent"], item["bChangeAmount"], item["bVolume"],
item["bAmplitude"], item["bHigh"], item["bLow"], item["bOpen"], item["bPreClose"]
))
self.conn.commit()
return item
def close_spider(self, spider):
self.cursor.close()
self.conn.close()
实验结果:
爬虫成功解析多只股票的完整行情数据,11 个字段全部准确写入 SQLite 数据库;Scrapy 的 Item 数据封装与 Pipeline 机制实现了解析逻辑与存储逻辑的解耦,项目结构清晰,具备良好的可扩展性。

2)心得体会
通过本次实验,我系统掌握了 Scrapy 框架的完整开发流程,理解了 Item、Spider、Pipeline 三大核心组件的分工与协作。相比于单文件脚本,Scrapy 的工程化结构更适合中大型爬虫项目,模块化的设计让代码维护和功能扩展更加方便。
实验中遇到了新版 Scrapy 响应编码属性只读的问题,通过手动解码响应体顺利解决,也让我积累了框架版本差异的处理经验。数据库存储管道的设计,实现了数据解析与持久化的分层解耦,符合软件工程的设计思想,也为后续多数据源、多存储方式的扩展打下了基础。
作业③:Scrapy 框架外汇牌价爬取
1)代码
数据模型items.py
import scrapy
class ForexScrapyItem(scrapy.Item):
Currency = scrapy.Field() # 货币名称
TBP = scrapy.Field() # 现汇买入价
CBP = scrapy.Field() # 现钞买入价
TSP = scrapy.Field() # 现汇卖出价
CSP = scrapy.Field() # 现钞卖出价
Time = scrapy.Field() # 发布时间
爬虫主程序 forex_spider.py
import scrapy
from forex_scrapy.items import ForexScrapyItem
class ForexSpider(scrapy.Spider):
name = "forex_spider"
allowed_domains = ["www.boc.cn"]
start_urls = ["https://www.boc.cn/sourcedb/whpj/"]
def parse(self, response):
# XPath定位牌价表格行,跳过表头
rows = response.xpath('//div[@class="BOC_main"]//table//tr[position() > 1]')
for row in rows:
currency = row.xpath('./td[1]/text()').get(default="").strip()
tbp = row.xpath('./td[2]/text()').get(default="").strip()
cbp = row.xpath('./td[3]/text()').get(default="").strip()
tsp = row.xpath('./td[4]/text()').get(default="").strip()
csp = row.xpath('./td[5]/text()').get(default="").strip()
publish_time = row.xpath('./td[7]/text()').get(default="").strip()
if not currency:
continue
item = ForexScrapyItem()
item["Currency"] = currency
item["TBP"] = tbp
item["CBP"] = cbp
item["TSP"] = tsp
item["CSP"] = csp
item["Time"] = publish_time
yield item
数据管道 pipelines.py
import sqlite3
class ForexDBSqlitePipeline:
def __init__(self):
self.db_path = "forex.db"
def open_spider(self, spider):
self.conn = sqlite3.connect(self.db_path)
self.cursor = self.conn.cursor()
self.cursor.execute("""
CREATE TABLE IF NOT EXISTS forex_rate (
id INTEGER PRIMARY KEY AUTOINCREMENT,
Currency TEXT NOT NULL,
TBP TEXT,
CBP TEXT,
TSP TEXT,
CSP TEXT,
Time TEXT
)
""")
self.conn.commit()
def process_item(self, item, spider):
self.cursor.execute("""
INSERT INTO forex_rate (Currency, TBP, CBP, TSP, CSP, Time)
VALUES (?,?,?,?,?,?)
""", (item["Currency"], item["TBP"], item["CBP"], item["TSP"], item["CSP"], item["Time"]))
self.conn.commit()
return item
def close_spider(self, spider):
self.cursor.close()
self.conn.close()
实验结果:
成功爬取数十条外汇牌价数据,所有字段与页面表格一一对应,数据完整写入 forex.db 数据库;XPath 定位表格数据精准高效,完全符合作业要求的 Scrapy+XPath + 数据库存储技术路线。

2)心得体会
本次外汇爬取实验让我进一步巩固了 Scrapy 框架的使用,也熟练掌握了 HTML 表格的 XPath 解析技巧。静态表格页面的数据提取,核心在于精准定位行与列的节点位置,通过调试 XPath 路径可以大幅提升解析效率与准确率。
两次 Scrapy 实验让我深刻体会到框架的优势:统一的请求管理、异常重试、日志统计等内置功能,让开发者不用重复造轮子,可以专注于数据解析逻辑本身。同时 Item 数据模型的标准化设计,保证了数据在 Spider、Pipeline 各组件间传递的一致性,降低了出错概率。后续也可以在此基础上扩展翻页爬取、定时采集等功能,进一步强化爬虫的实用性。
浙公网安备 33010602011771号