102302122许志安作业1

作业1

(1)爬取大学排名信息实验

import requests
from bs4 import BeautifulSoup

url = "http://www.shanghairanking.cn/rankings/bcur/2020"

res = requests.get(url)
res.encoding = 'utf-8' 

soup = BeautifulSoup(res.text, "html.parser")
rows = soup.select("tbody tr")

print("排名\t学校名称\t省市\t学校类型\t总分")

for row in rows:
    cols = row.find_all("td")
    rank = cols[0].text.strip()
    name = cols[1].text.strip().split('\n')[0] 
    province = cols[2].text.strip()
    type_ = cols[3].text.strip()
    score = cols[4].text.strip()
    print(f"{rank}\t{name}\t{province}\t{type_}\t{score}")

屏幕截图 2025-10-26 122906

屏幕截图 2025-10-26 115317

(2)心得体会

该实验核心在于:找到所指向数据在文本页下对应的表格位置,提取表格数据并遍历每行排版输出,考验了我们对requests , BeautifulSoup的使用。

作业2

(1)爬取商品名称和价格实验

import urllib3, re

url = "https://search.bl.com/k-%25E4%25B9%25A6%25E5%258C%2585.html"
html = urllib3.PoolManager().request("GET", url).data.decode("utf-8", "ignore")

names = re.findall(r'<div class="pro-img">.*?<img[^>]+(?:alt|title)="(.*?)"', html, re.S)
prices = re.findall(r'<div class="pro-money">.*?<div class="money-fl">¥\s*([\d\.]+)</div>', html, re.S)

for n, p in zip(names, prices):
    print(f"商品名: {n.strip()} | 价格: ¥{p.strip()}")

屏幕截图 2025-10-26 112707

屏幕截图 2025-10-26 115527

(2)心得体会

本次实验的核心在于:写出正确的正则表达式从网页源代码中提取商品名称和价格,考验了我们书写正则表达式的能力。

作业3

(1)爬取并下载图片实验

import urllib.request, re, os

html = urllib.request.urlopen("https://news.fzu.edu.cn/yxfd.htm").read().decode("utf-8")
urls = re.findall(r'src=["\']/?(__local/.*?\.(?:jpe?g|png))["\']', html, re.I)[:9]

if not urls: exit("未匹配到任何图片链接")
print(f"共找到 {len(urls)} 张图片,准备下载")

os.makedirs("images", exist_ok=True)
for i, u in enumerate(urls, 1):
    full = "https://news.fzu.edu.cn/" + u.lstrip("/")
    path = f"images/img_{i}{os.path.splitext(full)[1]}"
    print(f"下载第 {i} 张: {full} -> {path}")
    try: urllib.request.urlretrieve(full, path)
    except Exception as e: print("下载失败:", e)

print("下载完成!图片已保存在 ./images 文件夹中")

屏幕截图 2025-10-26 123301

屏幕截图 2025-10-26 115657

(2)心得体会

该实验的核心同样是使用正确的正则表达式匹配对应网页图片链接,其中有许多多余图片,要能匹配到关键,写出合适的正则表达式,并下载图片,考验我们的书写应变能力。

posted @ 2025-10-26 12:51  许志安xza  阅读(9)  评论(0)    收藏  举报