数据采集融合第一次实践作业

2026 数据采集与融合技术第一次作业

姓名:叶思铖
学号:102402141
课程:2026 数据采集与融合技术
作业要求:https://edu.cnblogs.com/campus/fzu/2026DataCollectingandFusionTechnology/homework/16746

开发环境与代码规范

  • Python 3.12;
  • requests、BeautifulSoup4;
  • 使用小写英文和下划线命名变量、函数,函数名体现功能;
  • 每个主要函数都有注释或文档字符串,说明输入、处理过程和输出;
  • 使用异常处理、请求超时和有限重试,保证程序能够正常结束;
  • 完整代码文件:assignment1_spider.py。

安装依赖:

python -m pip install -r requirements.txt

一、作业①:大学排名数据采集

1. 作业代码和运行结果

题目要求:使用 requests 和 BeautifulSoup 定向爬取
http://www.shanghairanking.cn/rankings/bcur/2020,屏幕打印大学排名信息。

核心代码如下,完整实现见 assignment1_spider.py:

import requests
from bs4 import BeautifulSoup

url = "http://www.shanghairanking.cn/rankings/bcur/2020"
response = requests.get(
    url,
    headers={"User-Agent": "Mozilla/5.0"},
    timeout=30,
)
response.raise_for_status()
soup = BeautifulSoup(response.text, "html.parser")

rows = soup.select("table.rk-table tbody tr")
result = []
for row in rows[:50]:
    cells = row.find_all("td")
    if len(cells) < 5:
        continue
    school = row.select_one(".name-cn").get_text(" ", strip=True)
    result.append({
        "排名": cells[0].get_text(" ", strip=True),
        "学校名称": school,
        "省市": cells[2].get_text(" ", strip=True),
        "学校类型": cells[3].get_text(" ", strip=True),
        "总分": cells[4].get_text(" ", strip=True),
    })

print("排名 | 学校名称 | 省市 | 学校类型 | 总分")
for item in result:
    print(item)

运行命令:

python assignment1_spider.py --task ranking --ranking-limit 50

程序同时把结果保存到 outputs/ranking.csv,字段为“排名、学校名称、省市、学校类型、总分”。

de0f7d91995cf852ac24f63d3081b91a
675baeb338ddc2d11beca5d67cd59911

2. 作业心得体会

本题让我熟悉了使用 requests 获取网页、使用 BeautifulSoup 定位表格以及清洗文本的基本流程。网页中的学校名称、排名和分数位于不同的 HTML 标签中,不能只依赖固定字符串位置。通过选择器定位表格行,再逐个读取单元格,可以让代码更容易理解和维护。保存为 CSV 后,数据也方便在 Excel 中查看和继续分析。

二、作业②:商城“书包”商品比价

1. 作业代码和运行结果

题目要求:使用 requests 和 re 设计一个自选商城商品比价爬虫,以“书包”为关键词,爬取商品名称和价格。本次选择当当网搜索页。

核心代码如下:

import re
import requests
from bs4 import BeautifulSoup
from urllib.parse import urlencode

url = "https://search.dangdang.com/?" + urlencode({
    "key": "书包",
    "page_index": 1,
})
response = requests.get(
    url,
    headers={"User-Agent": "Mozilla/5.0"},
    timeout=30,
)
response.raise_for_status()
soup = BeautifulSoup(response.text, "html.parser")

result = []
for index, product in enumerate(soup.select("ul.cloth_shoplist li"), start=1):
    title_node = product.select_one("a[name='itemlist-title']")
    price_node = product.select_one(".price_n")
    if not title_node or not price_node:
        continue
    price_match = re.search(
        r"(\d+(?:\.\d{1,2})?)",
        price_node.get_text(" ", strip=True),
    )
    if price_match:
        result.append({
            "序号": index,
            "价格": price_match.group(1),
            "商品名": title_node.get("title") or title_node.get_text(strip=True),
        })

print("序号 | 价格 | 商品名")
for item in result:
    print(item)

运行命令:

python assignment1_spider.py --task shop --keyword 书包 --shop-pages 1 --shop-limit 30

程序按题目要求将结果保存到 outputs/shop_prices.csv,表头为“序号、价格、商品名”;商品链接等辅助字段保存在 outputs/shop_prices_detail.csv。

image

image

2. 作业心得体会

本题重点练习了正则表达式和网页字段配对。商品价格中包含货币符号和空白字符,因此先用正则表达式提取数值,再进行保存。不同商城的页面结构不完全相同,选择服务端已经返回商品列表的页面,可以减少动态渲染带来的解析问题。实际编写时还需要控制请求次数,避免频繁访问目标网站。

三、作业③:网页图片采集

1. 作业代码和运行结果

题目要求:爬取指定网页 https://news.fzu.edu.cn/yxfd.htm 或自选网页中的所有 JPEG、JPG、PNG 图片,并保存到一个文件夹中。

核心代码如下:

from pathlib import Path
from urllib.parse import urljoin, urlparse
import requests
from bs4 import BeautifulSoup

page_url = "https://news.fzu.edu.cn/yxfd.htm"
response = requests.get(
    page_url,
    headers={"User-Agent": "Mozilla/5.0"},
    timeout=30,
)
response.raise_for_status()
soup = BeautifulSoup(response.text, "html.parser")

save_dir = Path("outputs/images")
save_dir.mkdir(parents=True, exist_ok=True)
count = 0
for image in soup.find_all("img"):
    image_url = image.get("src") or image.get("data-src")
    if not image_url:
        continue
    image_url = urljoin(page_url, image_url)
    if not image_url.lower().split("?", 1)[0].endswith((".jpg", ".jpeg", ".png")):
        continue
    image_data = requests.get(image_url, timeout=30).content
    count += 1
    suffix = Path(urlparse(image_url).path).suffix.lower()
    (save_dir / f"image_{count:03d}{suffix}").write_bytes(image_data)
    print(image_url)

实际脚本还增加了相对路径补全、懒加载属性、重复链接去重、响应类型判断和下载清单保存。运行命令:

python assignment1_spider.py --task images --image-limit 0

图片保存到 outputs/images/,下载链接和本地文件名保存到 outputs/downloaded_images.csv。

image

image

image

2. 作业心得体会

本题让我认识到网页中的图片链接既可能是绝对路径,也可能是相对路径或懒加载属性。使用 urljoin 统一补全链接后,才能正确下载图片。下载文件时还要检查扩展名和响应类型,避免把不符合要求的文件误保存。通过生成下载清单,可以核对网页链接和本地文件之间的对应关系。

完整运行与结果目录

一次运行三个任务:

python assignment1_spider.py --task all --ranking-limit 50 --shop-pages 1 --shop-limit 30 --image-limit 0

结果目录:

outputs/
├── ranking.csv
├── shop_prices.csv
├── shop_prices_detail.csv
├── downloaded_images.csv
└── images/
posted @ 2026-10-16 18:36  yesx  阅读(8)  评论(0)    收藏  举报