作业①
实验:爬取软科排名的大学信息
code
import requests
import bs4
from bs4 import BeautifulSoup
unilist = [] # 用于存储爬取的学校信息的空列表
url = "https://www.shanghairanking.cn/rankings/bcur/2020"
html = requests.get(url,timeout = 30)
html.raise_for_status()
html.encoding = html.apparent_encoding
soup = BeautifulSoup(html.text,"html.parser")
for tr in soup.find('tbody').children:
if isinstance(tr,bs4.element.Tag):
a = tr('a')
tds = tr('td')
unilist.append([tds[0].text.strip(), a[0].string.strip(), tds[2].text.strip(),
tds[3].text.strip(), tds[4].text.strip()])
# 查阅网页的HTML后分别取出所需的、藏在对应标签后面的内容
print("排名\t学校名称\t\t省市\t\t学校类型\t\t总分") # 输出格式
for i in range(0,16): # 学号102102116尾号16 这里只输出前16
x = unilist[i]
print("%s\t\t%s\t\t\t%s\t\t%s\t\t%s" % (x[0],x[1],x[2],x[3],x[4]))
#将信息按照对应的格式进行输出
- 运行结果:

实验心得
- 收获:对request方法和BeautifulSoup方法的爬虫有更为深入的理解与认识!同时使用BeautifulSoup方法前可以先查阅相应的HTML内目标标签的特点、规律,便于爬虫代码的简化。但输出格式没有调整到位,使用制表符仍存在不对其的情况。
作业②
实验:爬取商城商品的名称与价格
- 要求:用requests和re库方法设计某个商城(自已选择)商品比价定向爬虫,爬取该商城,以关键词“书包”搜索页面的数据,爬取商品名称和价格。
- 输出信息:
序号 价格 商品名
1 65.00 xxx
2......
- 具体代码:
code
import requests
from bs4 import BeautifulSoup
price = []
title = []
url = "http://search.dangdang.com/?key=%CA%E9%B0%FC&act=input&page_index=1"
html = requests.get(url,timeout = 30)
html.raise_for_status()
html.encoding = html.apparent_encoding
soup = BeautifulSoup(html.text,"html.parser")
list1 = soup.find_all('span','price_n')
for i in list1:
price.append(str(i).split('>')[1].split('<')[0])
list2 = soup.find_all('a', {"name":"itemlist-title"})
for i in list2:
title.append(i["title"])
print("{:1}\t\t{:1}\t\t{:1}".format("序号","商品名称","价格"))
for i in range(len(title)):
print(f"NO.{i}\t{title[i]}\t{price[i]}")
- 运行结果:

实验心得
- 收获:对商城网页的商品爬取到的信息可以先转化为字符串类型,进一步使用str类型的split()方法进行切割、提取我们所需的部分;对于find_all()方法返回值存储在列表里,但列表里的元素是标签属性,可以通过字典键值对的方式输入"key",直接获取所需的"value"避免切割方法的不便利!(具体体现在代码的备注当中)
实验③
实验:爬取给定网页所有JPEG、JPG格式文件
code
from bs4 import BeautifulSoup
import requests
url = "https://xcb.fzu.edu.cn/info/1071/4481.htm"
html = requests.get(url)
html.raise_for_status()
html.encoding = html.apparent_encoding
soup = BeautifulSoup(html.text,"html.parser")
list = soup.find_all('img')
path = []
for j in range(len(list)):
i = list[j]
img_url = "https://xcb.fzu.edu.cn" + str(i).split(' ')[1].split('"')[1]
with open(f".\pic\{j+1}.jpeg","wb") as f:
content = requests.get(img_url)
f.write(content.content)
print("下载成功!")
- 运行结果:

实验心得
- 收获:实验三容易受到网速的影响,最开始使用校园网进行实验会发现爬取速度特别慢,改用连接热点后可以快速爬取出所要的图片。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)